实现一个案例如下:
代码如下:
store.js
reducer1.js
reducer2.js
组件
import { Component } from "react";
import todoStore from './todoStore'
export default class RouterALL extends Component {
state = todoStore.getState()
render() {
todoStore.subscribe(this.update.bind(this))
console.log(this.state)
let inputVal = this.state.inputReducer.getIn(['inputVal'])
let list = this.state.liReducer.getIn(['list'])
return (
<div>
<input value={inputVal} onChange={this.handleChange.bind(this)}></input> <button onClick={this.add.bind(this)}>添加</button>
{ list.map((item,index)=>{
return <li key={index}>{item}<button onClick={()=>{
this.deleteItem(index)
}}>删除</button></li>
})}
</div>
)
}
handleChange(e){
let action ={
type:'INPUT',
value:e.target.value
}
todoStore.dispatch(action)
}
add(){
let action = {
type:'ADD',
value:this.state.inputReducer.getIn(['inputVal'])
}
todoStore.dispatch(action)
}
update(){
this.setState(todoStore.getState())
}
deleteItem(index){
console.log(index,3333)
let aa ={
type:'DELETE',
value:index
}
todoStore.dispatch(aa)
}
}