- store
import { createStore } from 'redux' // 引入createStore方法
import reducer from './reducer'
const store = createStore(reducer) // 创建数据存储仓库
export default store //暴露出去
- reducer
const defaultState = {} //默认数据
export default (state = defaultState, action)=>{ //就是一个方法函数
// console.log(state, action)
return state
}component
import store from './store'
constructor(props){
super(props)
//关键代码-----------start
this.state=store.getState();
//关键代码-----------end
console.log(this.state)
}onClick 执行的方法
changeInputValue(e){
const action ={
type:'changeInput',
value:e.target.value
}
store.dispatch(action)
}reducer 改变state
export default (state = defaultState, action)=>{
if(action.type === 'changeInput'){
let newState = JSON.parse( JSON.stringify (state)) //深度拷贝state
newState.inputValue = action.value
return newState
}
return state
}更新 component
constructor(props){
super(props)
this.state=store.getState();
this.changeInputValue= this.changeInputValue.bind(this)
//----------关键代码-----------start
this.storeChange = this.storeChange.bind(this) //转变this指向
store.subscribe(this.storeChange) //订阅Redux的状态
//----------关键代码-----------end
}
storeChange(){
this.setState(store.getState())
}