redux模块化demo
生活随笔
收集整理的這篇文章主要介紹了
redux模块化demo
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
store.js 在redux中 store 是唯一的。
import {createStore} from 'redux'; import reducer from './reducer' // 引入后的reducer store是唯一的 const store = createStore(reducer);export default store;reduce.js? 合并所以reducer
import {combineReducers} from 'redux'; import numReducer from './num/reducer' import todosReducer from './todos/reducer'; // 拿到單個模塊的reducer 進行合并 傳給store let reducer = combineReducers({num:numReducer,todos:todosReducer });export default reducer;在todos模塊(文件夾)下
state.js
// 用來存儲當前模塊下的數據 const state = {list:[],count:0 }export default state;reducer.js
// 將state導入 建立reducer函數 import _state from './state';let reduce = (state=_state,action)=>{console.log(action);let newState = {...state};if(action.type==='ADD'){newState.count = ++newState.count;newState.list.push(action.title)}return newState; } // reducer 用來處理state里面的數據 數據的驗證是通過action這個參數里的type進行的。 // action這個參數的傳遞是通過store.dispatch來分發(fā)的。 export default reduce;action.js
// 主要作用是返回一個對象 讓actions 來使用 // p 是傳遞的參數 const action = {ADD(p){return {type :'ADD', //這里的ADD的type是與reducer里的驗證有關 title:p}} } export default action;actions.js
import action from './action'; import store from '../store'; // 將傳遞的action參數引入 // 將store引入 把action參數傳給reducer。 const actions = {// p 是頁面?zhèn)鱽淼闹?/span> addItem(p){// 將action的里面對象傳遞參數let act = action.ADD(p);// 使用store把action里面的對象 作為參數傳遞過去 store.dispatch(act);} }export default actions;?App.js
import React, { Component } from 'react'; import './App.css'; import store from './redux/store' import actions from './redux/num/actions' import actions1 from './redux/todos/actions' // ui 組件 只取數據 class App extends Component {constructor(props){super(props);this.state = {n:store.getState().num.n,list:store.getState().todos.list}store.subscribe(()=>{//只要數據變化了這個回調函數就會執(zhí)行this.setState({n:store.getState().num.n});this.setState({list:store.getState().todos.list})})this.inc = this.inc.bind(this);this.add = this.add.bind(this);}inc(){// console.log(actions.dispatchAction) actions.dispatchAction()}add(){actions1.addItem(this.node.value);this.node.value = '';}render() {return (<div className="App" onClick={this.inc}>{ this.state.n}<input type="text" ref={node=>this.node=node}/><button onClick={this.add}>add</button> {this.state.list.map((item,index)=>{return (<div key={index}>{item}</div> )})}</div> );} }export default App;?
轉載于:https://www.cnblogs.com/l8l8/p/9482302.html
總結
以上是生活随笔為你收集整理的redux模块化demo的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 蓝牙stack bluez学习(1)St
- 下一篇: (转)C# Delegate.Invok