导图:
1.首先使用谷歌浏览器安装插件工具redux DevTools
更多工具----扩展程序----打开Chrome网上应用店----Redux DevTools
2.安装好之后在store文件夹下的index.js中的createStore中添加
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
index.js完整代码:
//引入redux
import { createStore } from 'redux';
import reducer from './reducer';
//定义store
const store = createStore(reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
export default store;
3.需要将input输入框中的内容改变并在redux中显示
- 在input中添加onChange事件:
onChange={this.handleInputChange}
, - 在construct中添加代码
this.handleInputChange = this.handleInputChange.bind(this);
使onChange的this指向一致 - 在handleInputChange方法中使用action把需求传递给store
handleInputChange(e) {
const action = {
//type:指需要改变的东西
type: 'change_input_value',
value:e.target.value
}
//通过dispatch(action)把数据传递给store
store.dispatch(action);
}
- store接收到dispatch(action)的数据直接将之传递给reducer
- reducer接收到数据通过if条件判断
//如果action的type类型是之前定义的change_input_value,那么对state数据做一个深拷贝,
//然后把action的value传递给新的value,
//返回最新的newState数据
if (action.type === 'change_input_value') {
//对之前的state值做一个深拷贝
const newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState;
}
- 使用store.subscribe来接收已经改变的数据并映射到页面
- 在 constructor中添加
-store.subscribe(this.handleStoreChange);
- handleStoreChange方法中:
handleStoreChange() {
//当感知到store数据发生变化的时候,调用getStore方法重新取数据并替换原来的数据
this.setState(store.getState())
}
4.点击按钮将输入框中的输入内容成为一个新的列表项并添加到列表中
- 在button中添加一个onClick方法
<Button type="primary" onClick={this.handleBtnClick}>提交</Button>
- 修改onClick方法的this指向
this.handleBtnClick = this.handleBtnClick.bind(this);
- 构造action将需求传递给store
handleBtnClick() {
const action = {
type: 'add_todo_item',
};
store.dispatch(action);
}
- reducer.js文件中判断action类型并且将获取到的inputValue值插入到list列表中
if (action.type === 'add_todo_item') {
const newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue);
//更新文本框的内容使之为空
newState.inputValue = '';
return newState;
}