react redux学习(一)

项目目录

《react redux学习(一)》

1、安装redux yarn add redux

2、创建store

  1. 列表项目创建store文件夹
  2. 文件夹下创建index.js
  3. index.js
         import { createStore } from 'redux';
         const store = createStore();
         export default store;

3、创建reducer.js

        const defaultState = {
            inputValue:""
        }
        export default (state = defaultState,action) => { return state }

reducer必须是纯函数,纯函数给定输入,固定输出,并且不能改变输入

5、store中如何获取reducer的数据,及改变

    //index.js做如下修改
    import { createStore } from 'redux';
    import reducer from './reducer'
    const store = createStore(reducer);
    export default store;

6、组件中如何获取store数据

  • 组件中引入store文件下的index.js
  • 在constructor中 this.state = store.getState();

7、如何改变store的数据

  • 创建action const action = { type:’input_action’,val:val};
  • store.dispatch(action) -> store ->reducer改变store数据 返回一个新的state数据

8、如何监听 store的数据改变,刷新dom

  • 组件中的constructor使用 store.subscribe(this.listener.bind(this));
  • listener () { this.setState(store.getState())};

9、优化action的type,报错可以定位

  • 创建actionTypes.js
  • export const CHANGE_INPUT_VALUE = “change_input_value”;

10、优化actionCreator.js,统一管理组件的action

    import { CHANGE_INPUT_VALUE} from './actionTypes'
    export const changeFocuse = (inputValue) => ({
        type:CHANGE_INPUT_VALUE,
        inputValue
    });

11、优化reducer.js

    import { CHANGE_INPUT_VALUE} from './actionTypes'
    const defaultState = {
        inputValue:""
    }
    export default (state = defaultState,action) => { 
        switch (action.type){
            case CHANGE_INPUT_VALUE:
                const newState = JSON.parse(JSON.stringify(state));
                newState.inputValue = action.inputValue;
                return newState;
            default:
                return state
        }
    }
    原文作者:前端
    原文地址: https://segmentfault.com/a/1190000018816168
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞