redux中的store使用(2)

导图:
在这里插入图片描述
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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值