|
- redux 正常使用
-
- 其实推荐了一个 chrome 拓展程序 [其中虽然store 被改变 ,但是 斌没有对其文件有任何操作]
-
- 1. 通过 dispatch(action) 向 store 传递 一个action 的json 字符串
- 2. store 会在reducer 中 处理接收 这个action
- 3. redecer 处理完的newState 返回给 store
- 4. 模块订阅监听 store 的变化 并给出一个处理的 function
- 5. 在处理的 function 中 进行对该模块的操作 ,大部分是直接this.setState( store.getState() )
复制代码 上代码:
模块:
- import React , { Fragment, Component }from 'react';
- import Mitem from './Mitem';
- // 第三步 引入 仓库
- import store from '../store/Store';
- class Mydo extends Component{
- // 构造函数
- constructor(props)
- {
- super(props);
- // 第四步 获取仓库的内容 利用 store.getState方法
- // console.log( store.getState() );
- this.state =store.getState();
- console.log(this.state.inpValue)
- this.lmStoreChange = this.lmStoreChange.bind(this);
- // 此处加个监听订阅
- store.subscribe(this.lmStoreChange);
- }
- lmStoreChange(){
- console.log(store.getState());
- // 这里其实还缺少一个对list 的操作,但是我不想管
- this.setState(store.getState())
- }
- // 监听input改变
- inpC(e){
- // this.setState({
- // inpValue:e.target.value
- // })
- // console.log(e.target.value)
- let action = {
- type :'chang_inp_value',
- value:e.target.value
- }
- // 传给数据处理中心中心 利用 dispatch 方法
- store.dispatch(action);
-
- }
- ………………
复制代码
继续代码 reducer
- // 这是一个处理器 用来 对 store 进行对应的操作;
- // 这个defaulState 只是一个测试的值 其实只要返回下面的就可以
- const defaultState ={
- t:[],
- lm:111,
- inpValue : '123',
- arr:[]
- };
-
- export default ( state=defaultState, action )=>{
- if(action.type == 'chang_inp_value')
- {
- // 这个步骤,视频里 说是拷贝,对json 的 解析 属于脱裤子放屁的 “深拷贝”
- let newState = JSON.parse(JSON.stringify(state));
- newState.inpValue = action.value;
- // 这里的return 其实是修改掉落 newState 的值 ,在模块中设定了监听函数 store.subscribe(this.lmStoreChange); 就可以实时进行更新
- return newState;
- }
- return state;
- };
复制代码
|
|