在 Redux 中,在这种情况下我是否必须导入商店才能访问数据?
In Redux, do I have to import store to access data in this case?
这是我的容器:
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;
}
发生这种情况是因为 javacript 的异步性质,您确实应该尝试从 componentWillReceiveProps
调用 getId 函数
componentWillReceiveProps(nextProps) {
if(nextProps.id !== this.props.id)
this.getId(nextProps)
}
getId(props) {
console.log(props.id)
}
如果您使用的是 redux thunk,您还可以在 setId 上使用 .then
回调,例如
setId(id) {
this.props.setId(id).then(() => {this.getId()}); //calls an action creator
}
这是我的容器:
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;
}
发生这种情况是因为 javacript 的异步性质,您确实应该尝试从 componentWillReceiveProps
componentWillReceiveProps(nextProps) {
if(nextProps.id !== this.props.id)
this.getId(nextProps)
}
getId(props) {
console.log(props.id)
}
如果您使用的是 redux thunk,您还可以在 setId 上使用 .then
回调,例如
setId(id) {
this.props.setId(id).then(() => {this.getId()}); //calls an action creator
}