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来分发的。
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 是页面传来的值
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(()=>{
//只要数据变化了这个回调函数就会执行
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;