编写Action和Reducer-添加函数
时间:2023-03-28 14:26:56
HTML
1.MainPageContentTransformation接下来,我们使用action和reducer来来回传递这个组件的数据。首先,让我们修改TodoList.js文件。具体代码如下:importReact,{Component}from'react';import'antd/dist/antd.css';import{Input,Button,List}from'antd';importstorefrom'./store';classTodoList扩展组件{constructor(props){super(props);this.state=store.getState()this.handleInputChange=this.handleInputChange.bind(this)this.handleStoreChange=this.handleStoreChange.bind(this)this.handleBtnClick=this.handleBtnClick.bind(this)store.subscribe(this.handleStoreChange)}render(){return(提交
{item}}/>
)}handleInputChange(e){//在react中,action是对象的形式//type的目的是告诉react,你帮我改变input的值,也就是后面的值,也就是e.target.valueconstaction={type:'change_input_value',value:e.target.value}store.dispatch(action)//console.log(e.target.value)}handleStoreChange(){//当store数据改变时,再调用store.getState方法再次从store中获取数据,//然后调用setState替换当前store中的数据this.setState(store.getState())}handleBtnClick(){constaction={type:'add_todo_item'}store.dispatch(action)}}exportdefaultTodoList;接下来我们来分析一下上面的代码。首先,每个动作都会先绑定对应的事件,然后,在事件中,创建动作。至于创建的action,目的是告诉react帮助action改变某个值,这个值就是它绑定的值。前端训练结束,要做的action就结束了,它的数据需要存储到store中。所以使用store.dispatch(action)进行处理,将action的数据传递给store。2.改变动作中的数据对于动作的初始值是固定的。但是有时候我们想修改action中的值,这时候就需要用到reducer了。现在,我们对reducer.js文件进行改造,让输入框可以自由输入值,同时在点击提交按钮后,添加列表操作。具体代码如下:constdefaultStore={inputValue:'123',list:[1,2]};//reducer可以接收状态,但不得修改状态constreducer=(state=defaultStore,action)=>{if(action.type==='change_input_value'){constnewState=JSON.parse(JSON.stringify(state));newState.inputValue=action.value;returnnewState;}if(action.type==='add_todo_item'){constnewState=JSON.parse(JSON.stringify(state));newState.list.push(newState.inputValue);newState.inputValue='';console.log(newState);returnnewState;}返回状态;}导出默认减速器;3、store数据改造接下来我们看一下store文件夹下index.js的内容。我们需要做一个简单的修改,具体代码如下:import{createStore}from"redux";从'./reducer'导入减速器;conststore=createStore(reducer,window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__());导出默认存储;除了reducer,我们还需要传入window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__()并调用这个方法。