利用redux-reduce管理数据,数据共享

1.概念:利用redux组件之间的传值非常简单,redux里面要求我们把数据都放在一个公共的存储区域store里面,组件之中尽量少放数据,也就是所有数据都不放在组件自身了,都把它放到一个公用的存储空间里面,然后组件改变数据就不需要传递了,改变store里面的数据之后其它的组件会感知到里面的数据发生改变。这样的话不管组件的层次有多深,但是走的流程都是一样的,会把数据的传递简化很多。

2:原理图利用redux-reduce管理数据,数据共享_第1张图片
3.代码目录

利用redux-reduce管理数据,数据共享_第2张图片
public文件


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
head>
<body>
    <div id="root">div>
body>
html>

src文件夹

containers文件夹

Count组件

import React, {
      Component } from 'react'
import {
     increment,decrement,incrementAsync} from '../../redux/actions/count'

//引入connect用于连接UI组件与redux
import {
     connect} from 'react-redux'


class Count extends Component {
     
    //加法
    increment = ()=>{
     
        const {
     value} = this.selectNumber
        this.props.increment(value*1)
    }
    //减法
    decrement = ()=>{
     
        const {
     value} = this.selectNumber
        this.props.decrement(value*1)
    }
    incrementIfOdd = ()=>{
     
        // const {value} = this.selectNumber
    }
    //异步加
    incrementAsync = ()=>{
     
        const {
     value} = this.selectNumber
        this.props.incrementAsync(value*1)

    }
    render() {
     
        return (
            <div>
                <h1>当前求和为:{
     this.props.count},下方组件总人数:{
     this.props.renshu}</h1>
                <select ref={
     c => this.selectNumber = c}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                </select>
                <button onClick={
     this.increment}>+</button>
                <button onClick={
     this.decrement}>-</button>
                <button onClick={
     this.incrementIfOdd}>当前求和为奇数再加</button>
                <button onClick={
     this.incrementAsync}>异步加</button>
            </div>
        )
    }
}
export default connect(
    state => ({
     count:state.count,renshu:state.rens.length}),


    //最终返回一个action,react-redux会自己将得到的action 分发
        {
     
            increment,
            decrement,
            incrementAsync
        }
)(Count)

Person组件

import React, {
      Component } from 'react'
import {
     nanoid} from 'nanoid'
import {
     connect} from 'react-redux'
import {
      createAddPersonAction } from '../../redux/actions/person'


class Person extends Component {
     

    addPerson = ()=>{
     
        const name = this.nameNode.value
        const age = this.ageNode.value
        const personObj = {
     id:nanoid(),name,age}
        this.props.jiaYiRen(personObj)
    }

    render() {
     
        return (
            <div>
                <h2>我是person组件</h2>
                <input ref={
     c=>this.nameNode = c} type="text" placeholder="输入名字"/>
                <input ref={
     c=>this.ageNode = c} type="text" placeholder="输入年龄"/>
                <button onClick={
     this.addPerson}>添加</button>
                <ul>
                    {
     
                        this.props.yiduiren.map((p)=>{
     
                            return <li key={
     p.id}>{
     p.name}---{
     p.age}</li>
                        })
                    }
                </ul>
            </div>
        )
    }
}

export default connect(
    //state是redux保存的总状态对象
    state =>  ({
     yiduiren:state.rens}),
    {
     jiaYiRen:createAddPersonAction})(Person)
 

redux

action

count

// 该文件专门为count组件生成action对象
import {
     INCREMENT,DECREMENT} from '../constant.js'


//同步action,就是指action的值为Object类型的一般对象
export const increment = data =>({
     type:INCREMENT,data})
export const decrement = data =>({
     type:DECREMENT,data})

//异步action,就是指action的值为函数,异步action中,一般都会调用同步action
export const incrementAsync = (data,time) =>{
     
    return (dispatch) =>{
     
        setTimeout(()=>{
     
            dispatch(increment(data))
        },time)
    }
}

person

import {
     ADD_PERSON} from '../constant'

export const createAddPersonAction = personObj => ({
     type:ADD_PERSON,data:personObj})

reducers

count

// 该文件用于创建一个为Count组件服务的reducer,reducer本质就是一个函数
// reducer函数会接到两个参数,分别:之前的状态,动作对象
import {
     INCREMENT,DECREMENT} from '../constant'

const initState = 0;

//给preState默认值,initState,当第一次,传入的prestate为undefined,就会将默认值赋进去
export default function countReducer(preState = initState,action){
     
    console.log(`prevalue=${
       preState}`)
    const {
     type,data} = action
    switch(type){
     
        case INCREMENT:
        return preState + data
        
        case DECREMENT:
        return preState - data
        default:
        return preState
    }
}

index(汇总reducer

//引入,用于汇总
import {
     combineReducers} from 'redux'
import countReducer from './count'
import personReducer from './person'

//汇总所有reducer,变成一个总的reducer
export default combineReducers({
     
    count:countReducer,
    rens:personReducer
})

person

import {
     ADD_PERSON} from '../constant'

//初始化人的列表
const initState = [{
     id:'001',name:'tom',age:18}]
export default function personReducer(preState=initState,action){
     
    const {
     type,data} = action
    switch(type){
     
        case ADD_PERSON://若是添加一个人
            return [data,...preState]
        default:
            return preState 
    }
}

consatant

// 该模块用于定义action对象中的type类型的常量值,目的只有一个:便于管理的同时,防止程序员单词写错

export const INCREMENT = 'increment'
export const DECREMENT = 'devrement'
export const ADD_PERSON = 'add_person'

store

//该文件专门用于暴露一个store对象,整个应用只有一个store对象

//引入汇总之后的reducer
import reducer from './reducers/index'

//引入creatStore
import {
     createStore,applyMiddleware} from 'redux'
//引入redux-thunk,用于支持异步ACTION

import thunk from 'redux-thunk'

//引入redux-devtools-extension
import {
     composeWithDevTools} from 'redux-devtools-extension'
export default createStore(reducer,composeWithDevTools(applyMiddleware(thunk)))

APP.

import React, {
      Component } from 'react'
import Count from './containers/Count'
import store from './redux/store'
import Person from './containers/Person'

export default class App extends Component {
     
    render() {
     
        return (
            <div>
                {
     /* {给容器组件传递store} */}
               <Count store={
     store}/>
               <hr/>
               <Person/>
            </div>
        )
    }
}

index

import React from'react'
import ReactDom from 'react-dom'
import App from './App'
import store from './redux/store'
import {
     Provider} from 'react-redux'

ReactDom.render(
    //包裹APP,让app所有后代组件都能接受store
    <Provider store={
     store}>
        <App/>
    </Provider>,
document.getElementById('root'))

//监测redux中的状态改变,若redux的状态发生改变,重新渲染
// store.subscribe(()=>{
     
    // ReactDom.render(,document.getElementById('root'))
// })

你可能感兴趣的:(react,前端)