标签:有一个 update share component isp roc upd bre ima
redux的工程化管理
目录建设
store store中存放的是redux中使用的东西
直接看代码
App.js //(只用引入一行创建容器store的js就可以了) import ‘./store/index.js‘ store/index.js //(创建容器,传入合并好的reducer) import {createStore} from ‘redux‘ import reducer from ‘./reducer/index.js‘ let store = createStore(reducer); window.store = store; store/actionTypes.js //(定义所有的类型变量名) const VOTE_SUPPORT = ‘VOTE_SUPPORT‘; const VOTE_AGAINST = ‘VOTE_AGAINST‘; export { VOTE_SUPPORT, VOTE_AGAINST } store/action/vote.js //(按不同模块定义的不同的行为对象,返回相应的标识type类型) import * as TYPES from ‘../actionTypes.js‘ let vote = { support(){ return { type: TYPES.VOTE_SUPPORT } }, against(){ return { type: TYPES.VOTE_AGAINST } } }; export default vote; store/action/index.js //(导出不同模块的action对象) import vote from ‘./vote‘ import person from ‘./person‘ export default { vote, person } store/reducer/vote.js //(定义不同模块的自己的reducer) import * as TYPES from ‘../actionTypes.js‘ export default function vote(state = { n: 0, m: 0 }, action) { switch (action.type) { case TYPES.VOTE_SUPPORT: state.n = state.n + 1; break; case TYPES.VOTE_AGAINST: state.m = state.m + 1; break; } return state; } store/reducer/index.js //(利用combineReducers函数合并不同的reducer) import vote from ‘./vote‘ import person from ‘./person‘ import {combineReducers} from ‘redux‘ let reducer = combineReducers({ vote, person }); export default reducer; <Vote title={‘标题一‘}></Vote> //调用 vote.js import React from ‘react‘; import VoteBody from ‘./voteBody.js‘ import VoteFooter from ‘./voteFooter.js‘ class Vote extends React.Component{ constructor(){ super(); } render() { return ( <div> <VoteBody></VoteBody> <VoteFooter></VoteFooter> </div> ) } } export default Vote; voteFooter.js import React from ‘react‘; import action from ‘../store/action/index.js‘ class VoteFooter extends React.Component{ constructor(){ super() } render() { //获取不同模块自己的行为函数,执行后获取对应的标识 let {support, against} = action.vote; return ( <div> <button onClick={e => window.store.dispatch(support())}>赞成</button> <button onClick={e => window.store.dispatch(against())}>反对</button> </div> ) } } export default VoteFooter; VoteBody.js import React from ‘react‘; class VoteBody extends React.Component{ constructor(){ super() } componentDidMount() { window.store.subscribe(()=>{ this.forceUpdate(); }) } render() { //获取不同模块自己的state let {n, m} = window.store.getState().vote; return ( <div> <div>赞成{n}票</div> <div>反对{m}票</div> </div> ) } } export default VoteBody;
标签:有一个 update share component isp roc upd bre ima
原文地址:https://www.cnblogs.com/chaixiaozhi/p/12215116.html