前提警示:react、redux之间没有本质关系,redux能够结合其余库使用。redux数据管理方式跟react的数据驱动视图理念很合拍,一块儿使用,开发更加的便利高效react
// index.js 入口文件建立store实例 import {createStore} from 'redux' import reducer from './reducer.js' const store = createStore(reducer); export default store; // reducer.js 处理数据 const defaultState={ carList:[] } export default (state=defaultState, action)=>{ // 拷贝数据 修改数据 返回数据 const newState = JSON.parse(JSON.stringify(state)) if(action.type == 'add_car_item'){ newState.carList.push(action.data); return newState; } return state; }
import store from '../store/index'
import store from '../store/index' export default class Car extends Component { constructor(props){ super(props) this.state = store.getState(); // 监听store数据变化 this.watch = store.subscribe(this.changeState.bind(this)) } render() { return ( <div> 我是购物车页 </div> ) } changeState(){ this.setState(store.getState()) } componentWillUnmount(){ this.watch(); // 取消监听 防止内存泄漏 } }