美文网首页
在react cra项目中使用 react-redux

在react cra项目中使用 react-redux

作者: 高呼吾名 | 来源:发表于2019-07-28 13:37 被阅读0次

1、引入redux 和 react-redux

yarn add redux
yarn add react-redux

2、创建Reduce

reduce.js 函数名为自定义变量名,第一个参数state 实际上对应的是后边使用redux组件里的this.props, 第二个参数action是个对象,可以自定义属性操作这个reduce 方法,一般会包含{tyep:"string",value:"object"}

注意:Reduce 用来给State赋值的变量均必须为深拷贝对象,意思是这里的实参必须是从内存新开辟出来的地址,如果直接拿state的引用来操作会导致react检测不到新props而不重新渲染页面。

const testReducer = (state, action) => {
    if(!state){
        //初始化state 如果为null 生成一个初始化变量,用来存储数据
        state={arr:[]}
    }
    switch (action.type) {
      case 'ADD':
            // state.arr.push(action.value);
            const newArr = state.arr.slice(0);
            newArr.push(action.value);
            state.arr = newArr;
            return {...state};
      default:
        return {...state}
    }
}
export {testReducer};

3、创建store ,并引入Provider组件

import React from 'react';

import {Provider} from "react-redux"
import {testReducer} from "./reducer/testReducer.js"
import {createStore} from "redux";

const store = crerteStore(testReducer);
ReactDOM.render(
    <Provider store={store}>
        {/* 这里BrowserRouter是其他组件,跟Redux没关系 */}
        <BrowserRouter>
            <App></App>
        </BrowserRouter>
    </Provider>
, document.getElementById('root'));

4、在不同组件通过Redux来操作同一变量。demo:父子组件共同操作一个数组,父子组件都可以给这个数组添加内容,并在父组件渲染出数组内容


import React,{Component} from "react";
import {connect} from "react-redux"

class Children extends Component{
    render(){
        const{PushData}=this.props;
        return(<div style={{
            width:"200px",
            backgroundColor:"#79CDCD"
        }}>

            <button onClick={()=>{
                PushData("子组件添加的");
            }}>子组件按钮</button>
        </div>);
    }
}


class Parent extends Component{

    render(){
        const{PushData,arr}=this.props;
        let html = arr.map((item,i)=>(
            <h3 key={i}>{item}</h3>
        ));
        return (<div style={{
            width:"200px",
            backgroundColor:"#DAA520"
        }}>
            <button onClick={()=>{
                PushData("父组件添加的")
            }}>父组件按钮</button>
            {html}
            <br></br>
            <br></br>
            <Children></Children>
        </div>);
    }
}



const mapStateToProps = (state)=>{
    return {
        arr:state.arr
    }
}

const mapDispatchToProps = (dispatch)=>{
    return {
        PushData:(value)=>{
            dispatch({type:"ADD",value:value})
        }
    }
}

//要使用Redux的组件必须使用“react-redux”程序集下的connect方法包裹
Parent = connect(mapStateToProps,mapDispatchToProps)(Parent)
Children = connect(mapStateToProps,mapDispatchToProps)(Children)

export default Parent;

mapStateToProps 这个方法是将Reducer里定义的state和这个组件的this.props进行映射
mapDispatchToProps 是用来设置组件内操作Reducer里state的方法,其中PushData为方法名

相关文章

网友评论

      本文标题:在react cra项目中使用 react-redux

      本文链接:https://www.haomeiwen.com/subject/ygwurctx.html