react redux学习(一)

项目目录

图片描述

一、安装redux yarn add redux

二、建立store

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

三、建立reducer.js

const defaultState = {
            inputValue:""
        }
        export default (state = defaultState,action) => { return state }
reducer必须是纯函数,纯函数给定输入,固定输出,而且不能改变输入

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

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

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

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

七、如何改变store的数据

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

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

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

九、优化action的type,报错能够定位

  • 建立actionTypes.js
  • export const CHANGE_INPUT_VALUE = "change_input_value";

十、优化actionCreator.js,统一管理组件的actionredux

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

十一、优化reducer.jsdom

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
        }
    }
相关文章
相关标签/搜索