react学习(三)——redux的使用

redux是react的状态管理模块,他一共有四个核心模块:store,state,action,reduce。

store

仓库,一个应用只有一个 ,绑定在最外层上面

import {Provider} from 'react-redux'
import {store,persistor} from './redux'
function render(){
    return ReactDOM.render(<Provider store={store}><PersistGate persistor={persistor}><App/></PersistGate></Provider>, document.getElementById('root'));
}
render();
store.subscribe(render);//添加侦察器  能够在状态发生变化的时候让他自动响应

state

每个组件可以通过connect连接器来连接state以获取stroe 里面的数据(状态)

action

export const add = ()=>{
    return {type:'ADD',data:2}
};

export const minus = ()=>{
    return {type: 'MINUS',data:1}
};

reduce

键值对写法:

首先得有一个工具函数:

tool.js

export const createReduce = (initialState,handlers)=>{
    return function reducer(state = initialState, action) {
        if (handlers.hasOwnProperty(action.type)) {
            return handlers[action.type](state, action)
        } else {
            return state
        }
    }
};

然后reduce.js
import {createReduce} from "../tool";

//键值对 object 代替switch case 写法   多写一个工具函数createReduce
const count = createReduce(10,{
    "ADD":(state,action)=>{
        return ++state;
    },
    "MINUS":(state,action)=>{
        return --state;
    }
});

export default count

swaitch写法(条件多得时候就swaitch代替if啦):

const count = (state = 10, action) => {
    if (action.type === 'ADD') {
        state = ++state;
    } else if (action.type === 'MINUS') {
        state = --state;
    }
    return state;
};
export default count

两种写法具体有上面差异呢,个人理解得话是键值对写法上面更方便,可读性要高一点。性能上面没研究过,应该是差不多得

怎么触发:

view 视图层里面  

test.jsx

import {add, minus} from "../../redux/test/action";
import {connect} from "react-redux";
//映射state状态到组件
const mapStateToProps = (state)=>{
    return {
        count:state.test
    }
};
//映射dispatch分发函数到组件  
const mapDispatchToProps = (dispatch) => {
    return {
        add: () => {
            dispatch(add());
        },
        minus: () => {
            dispatch(minus());
        },
    }
};

export default connect(mapStateToProps,mapDispatchToProps)(Test);

按钮点击触发

<Button type="primary" htmlType="button" onClick={() => this.props.add()}>add</Button>
<Button type="primary" htmlType="button" onClick={() => this.props.minus()}>minus</Button>
<div>total:{parseInt(this.props.count)}</div>

说下更改状态的具体触发流程吧:通过dispatch->触发action->触发reduce->触发整体store->reduce里面重新返回更新后的数据

获取状态的流程:connect连接组件和store->mapStateToProps映射 state ->this.prop.映射的值 就能获取啦(this.props.count)

ps:本人萌新,有什么不对的,希望由大佬能够指出!感谢!

猜你喜欢

转载自blog.csdn.net/wangshang1320/article/details/88396735