- store
import { createStore } from 'redux' // 引入createStore方法
import reducer from './reducer'
const store = createStore(reducer) // 創(chuàng)建數(shù)據(jù)存儲(chǔ)倉庫
export default store //暴露出去
- reducer
const defaultState = {} //默認(rèn)數(shù)據(jù)
export default (state = defaultState, action)=>{ //就是一個(gè)方法函數(shù)
// console.log(state, action)
return state
}component
import store from './store'
constructor(props){
super(props)
//關(guān)鍵代碼-----------start
this.state=store.getState();
//關(guān)鍵代碼-----------end
console.log(this.state)
}onClick 執(zhí)行的方法
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)
//----------關(guān)鍵代碼-----------start
this.storeChange = this.storeChange.bind(this) //轉(zhuǎn)變this指向
store.subscribe(this.storeChange) //訂閱Redux的狀態(tài)
//----------關(guān)鍵代碼-----------end
}
storeChange(){
this.setState(store.getState())
}