0
這是我的容器:在Redux中,在這種情況下,是否必須導入存儲才能訪問數據?
this.setObj(obj)
let activeButton = 0;
anotherObj.options.forEach((option, index) => {
if (option.id === defaultId) {
activeButton = index;
this.setButton(index); //setButton is a common function, so I cannot pass obj as argument to it
}
});
setObj(obj) {
this.props.setObj(obj); //calls an action creator
}
setButton() {
let {obj} = this.props;
}
我的行動:
setObj = (obj) => ({
type: 'SET',
obj
})
我減速機:
switch(action.type) {
case 'SET':
return {...state, id: action.obj}
}
,我有mapStateToProps
和mapDispatchToProps
。
現在我找到了一個問題。 如果我在我的容器中調用setObj()
,然後再調用setButton()
,那麼obj
不會更新。根據丹,因爲它是異步的。 https://github.com/reactjs/react-redux/issues/291
所以在這種情況下,應該導入商店才能訪問最新的obj
?
import store from './store'
setButton() {
const state = store.getState()
let { obj } = state;
}
感謝您的快速響應。上面的代碼是一個簡化的代碼。在我的真實代碼中,我必須在'setId()'之後調用'getId()'。使用'store.getState()'是個好主意嗎? –
在這個[鏈接](https://github.com/reactjs/react-redux/issues/291)中,Dan Abramovic說: 因此調用調度將立即更新商店狀態,但您的組件將稍後更新同樣的勾號,在一起。因爲存儲狀態立即更新,如果我使用getState()我假設我可以得到最新的數據,對嗎? –
Dan是對的,但是您可以嘗試回撥方法 –