页面效果(一共是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({//合并reducertodos: 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.todosc: 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(()=>{//监听仓库数据改变,然后赋值给组件statethis.setState({todos: store.getState().todos.todos,c: store.getState().todos.todos.filter(v=>{return v.finished;}).length})console.log(store.getState())})}