redux的基础详解和使用方法

    xiaoxiao2022-06-25  229

    redux

    redux就是将组件的数据放到一个公共的store里,大家都可以去读取,把数据的传递简化了。一个组件改变了store的值,其他的组件就会知道,然后会去取改变之后的数据 redux=reducer+flux

    redux工作流

    Store的创建

    1、src目录下面创建store文件夹。 2、在store文件夹中,创建index,js用来创建公共仓库,代码如下

    import { createStore } from 'redux'; import reducer from './reducer' const store = createStore(reducer);//创建公共仓库 export default store;

    3、在store文件夹中,创建reducer.js,代码如下

    //reducer需要返回一个函数 //state就是整个仓库里存储的数据 const defaultState={ inputValue:"", list:[] }//默认不存储任何数据 export default (state=defaultState,action) => { return state }

    4、组件中引入

    import store from './store/index'

    5、读取store中的数据 组件中store.getState()就能获取到公共库中的所有存储字段 6、修改store中的数据 下面代码放到constructor

    this.handleStoreChange=this.handleStoreChange.bind(this) //store里面的内容只要被改变,这个函数就会被执行 store.subscribe(this.handleStoreChange)

    //放到方法里

    handleInputChange(e){ e.persist() console.log(e.target) const action = { type:"change_input_value",//告诉action要做啥 value:e.target.value } store.dispatch(action) } handleStoreChange(){ console.log("store change"+"=========") console.log(store.getState()) this.setState(store.getState())//重新获取更新state,新的state替换原来的state }

    reducer文件

    //reducer可以接收state,但是绝不能修改state 因此要去拷贝,改变新的state export default (state=defaultState,action) => { if(action.type=="change_input_value"){ //拷贝一份之前state里面的数据--深拷贝 const newState=JSON.parse(JSON.stringify(state)) newState.inputValue=action.value return newState; } return state }

    actionTypes的拆分

    其实就是将action的Type作为常量放到一个actionTypes.js中, 防止type太多导致的一些不必要的bug

    在组件中不断定义action的type,代码比较繁琐,这个时候可以使用actionCreators统一创建action

    eg创建actionCreators.js,代码如下 import { CHANGE_INPUT_VALUE, ADD_ITEM_TO_LIST, DEL_ITEM_FROM_LIST} from './actiontypes' export const getInpuChangeAction = (value) => ({ type:CHANGE_INPUT_VALUE, value }) export const addItemToList = () => ({ type:ADD_ITEM_TO_LIST, }) export const delItemFromList = (index) => ({ type:DEL_ITEM_FROM_LIST, index })

    组件中

    const action = addItemToList() store.dispatch(action)

    知识总结

    redux设计和使用三大原则 1、store是唯一的 2、只有store能够改变自己的内容 3、reducer必须是纯函数 纯函数是指给固定的输入就一定有固定的输出

    遇到的问题

    e.target是null 解决办法:在调用e.target之前调用e.persist() eg: e.persist() console.log(e.target)

    最新回复(0)