必威体育Betway必威体育官网
当前位置:首页 > IT技术

redux(二)reducer的合并与拆分

时间:2019-08-17 13:15:29来源:IT技术作者:seo实验室小编阅读:50次「手机版」
 

reducer

页面效果(一共是Todos和Number两个不相干的组件):

redux配置文件和组件结构:

相当于是在前一篇中的结构,将store.js和抽离了出来,并且将两个组件的reducer通过redux模块中的combineReducers方法将其合并为一个reducer文件,放在与store.js同级的store文件夹下:

合并两个组件的reducer.js:

import {combineReducers} from 'redux';
import todosReducer from './todos/reducer';
import numberReducer from './number/reducer';

let reducer = combineReducers({//合并reducer
	todos: todosReducer,
	number: numberReducer
})
export default reducer;

store.js中直接改为引用合并后的reducer:

import {createStore } from 'redux';
import reducer from "./reducer";//引入当前目录下合并后的rreducer
let store = createStore(reducer);
export default store;

合并reducer后再view中得更改

  constructor(props){
      super(props);
      this.state ={
        todos: store.getState().todos.todos,//将原来的store.getState().todos改为store.getState().todos.todos
        c: store.getState().todos.todos.filter(v=>{
              return v.finished;
           }).length
      }
      this.changeChexkbox = this.changeChexkbox.bind(this)
      this.removeItem = this.removeItem.bind(this)
  }

还有不要忘了将新state在store.subscribe函数中监听:

  componentWillmount(){
     store.subscribe(()=>{//监听仓库数据改变,然后赋值给组件state
        this.setState({
           todos: store.getState().todos.todos,
           c: store.getState().todos.todos.filter(v=>{
              return v.finished;
           }).length
        })
        console.log(store.getState())
     })
  }

相关阅读

分享到:

栏目导航

推荐阅读

热门阅读