P21:Redux进阶-React-redux的数据修改
上篇文章中我们已经可以用React-redux
顺利的拿到Store
中数据了。本文学习如何改变Store
中的数据。也就是当我们修改<input>
中的值时,去改变store
数据,UI界面也随之进行改变。
编写onChange响应事件
打开TodoList.js
文件,然后在<button>
上注册onChange
事件,这里我就偷懒直接绑定this
了。
<input value={this.props.inputValue} onChange={this.inputChange.bind(this)} />
这里先编写一个最简单的inputChange
方法。
inputChange(e){ console.log(e.target.value) }
然后到浏览器中的控制台就不再有报错,而且输入时可以打印出值,这说明我们的绑定成功了。这步完成我们要改为react-redux
的了。
编写DispatchToProps
要使用react-redux
,我们可以编写另一个映射DispatchToProps
,先看下面这段代码,你会发现有两个参数,第二个参数我们用的是null
。
export default connect(stateToProps,null)(TodoList);
DispatchToProps
就是要传递的第二个参数,通过这个参数才能改变store
中的值。
const dispatchToProps = (dispatch) =>{ return { inputChange(e){ console.log(e.target.value) } } }
有了这个参数之后可以把响应事件改成下面的代码.
<input value={this.props.inputValue} onChange={this.props.inputChange} />
然后把connect第二个参数传递过去。
export default connect(stateToProps,dispatchToProps)(TodoList);
这时候原来的inputChange
方法就没用了,可以删除掉。 目前整体的代码就改为下面的样子了,我们在浏览器中预览也是可以看到效果的。此步骤成功说明映射关系支持成功。
import React, { Component } from 'react'; import store from './store' import {connect} from 'react-redux' class TodoList extends Component { constructor(props){ super(props) this.state = store.getState() } render() { return ( <div> <div> <input value={this.props.inputValue} onChange={this.props.inputChange} /> <button>提交</button> </div> <ul> <li>mybj</li> </ul> </div> ); } } const stateToProps = (state)=>{ return { inputValue : state.inputValue } } const dispatchToProps = (dispatch) =>{ return { inputChange(e){ console.log(e.target.value) } } } export default connect(stateToProps,dispatchToProps)(TodoList);
派发action到store中
映射关系已经做好了,接下来只要进行action
的派发和reducer
对业务逻辑的编写就可以了。派发action和以前的流程一样,我就直接给出代码了。
const dispatchToProps = (dispatch) =>{ return { inputChange(e){ let action = { type:'change_input', value:e.target.value } dispatch(action) } } }
派发后就需求在reducer
里边,编写对应的业务逻辑了。
const defalutState = { inputValue : 'jspang', list :[] } export default (state = defalutState,action) =>{ if(action.type === 'change_input'){ let newState = JSON.parse(JSON.stringify(state)) newState.inputValue = action.value return newState } return state }
这样就算整个修改过程完成了,到浏览器中查看一下,应该就实现了改变input框的效果。这个流程你刚开始学会觉的很绕,但是你作的多了,你就会发现它很简单,就是一个模式,而且会降低程序出错的机率。建议这个流程你至少要写5遍以上,据我所知,几乎所有公司用react都会用到react-redux,所以这个流程重要性不次于Redux
的流程,一定要熟练掌握。