redux action的使用

继续上次的教程,还是先看图:

这次我们完成对reducer的修改,然后更新dom,文件目录结构如下

首先监听数据的改变,写好input组件的onchange方法

					<Input 
						value={this.state.inputValue} 
						placeholder='todo info' 
						style={
   
   {width: '300px', marginRight: '10px'}}
						onChange={this.handleInputChange}
					/>

然后再onchange方法中添加action 把这个动作派发给reducer, action是一个对象。首先需要定义action的type,这个就相当于名字,然后就是value值,把值传给reducer。

	handleInputChange(e) {
		const action = {
			type: 'change_input_value',
			value: e.target.value
		}
		store.dispatch(action);
	}

reduce接收到这个action进行处理,通过type判断改变谁的值。然后深拷贝jsson.stringify。然后将新的newstate返回。这里注意reduce不可以直接改变state的值。所以我们要先拷贝一份state,再将新的state return出去

	if (action.type === 'change_input_value') {
		const newState = JSON.parse(JSON.stringify(state));
		newState.inputValue = action.value;
		return newState;
	}

然后在todolist中,订阅store的改变。当reducer改变了 就会收到通知

	constructor(props) {
		super(props);
		store.subscribe(this.handleStoreChange);
	}

最后一步,收到store改变的通知,我们可以重新获取store中的state,然后出发setstate方法,重新触发render函数,刷新页面

	handleStoreChange() {
		this.setState(store.getState());
	}

猜你喜欢

转载自blog.csdn.net/lee727n/article/details/108863847