当您需要能够立即从props检索值时,我试图确定对await
来自React的动作调用是否有效。换句话说,请考虑以下示例:
// Import the Redux store directly (this is just to show that the store will update synchronously)
import store from '../store';
const state = store.getState();
// Where foo is an object created by combineReducers and bar is a property of foo with initial value of 'baz'
console.log(this.props.foo.bar); // Prints 'baz'
console.log(state.foo.bar); // Prints 'baz'
// Now, call the action to set bar to 'new value'
this.props.setBar('new value');
console.log(this.props.foo.bar); // Prints 'baz' (still the old value)
console.log(state.foo.bar); // Prints 'new value' (updated)
// Currently, this function call will fail because it finds the old value of bar. This is the point of needing the value immediately... This function will need to look for the updated value of bar in state. I can't pass the new value directly as a parameter, because the function may also need to be called in other situations where it's not readily available like this one.
doSomethingThatWillLookForBar();
这是我观察到的行为:操作是同步的,并且Redux存储是同步更新的,但是组件是异步更新的。看着调试器,我可以看到道具已正确更新,因此mapStateToProps
可以正常工作,而不能同步。如果是这样,它将像setState
一样。设置状态时,如果立即需要获取更新的状态,则需要await
setState
或使用setState
的回调参数。所以...当我await
进行动作调用时,它可以正常运行:
// Before action call
console.log(this.props.foo.bar); // Prints 'baz'
console.log(state.foo.bar); // Prints 'baz'
// Now, call the action with an await
await this.props.setBar('new value');
console.log(this.props.foo.bar); // Prints 'new value' (updated)
console.log(state.foo.bar); // Prints 'new value' (updated)
所以,这很好用,但是我在文档中找不到任何东西来确认这样做是可以接受的。我发现的所有内容都表明Redux操作应该完全同步(除非使用Thunk中间件发送异步操作)。这使我怀疑是什么地方出了问题。我猜我的用法是正确的,而文档中的这一遗漏只是因为文档假定您通常不需要立即从props中获取设置的值(因为您已经设置了它,所以应该已经准备好了) 。因此,在假定它是正确的并继续前进之前,只需尝试获得一些确认,这是预期的行为即可。
作为参考,这是我对connect
函数的使用:
const mapStateToProps = state => ({
foo: state.foo
});
const mapDispatchToProps = dispatch => {
return {
setBar: (value) => {
dispatch(setBar(value))
}
}
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Foo);
答案 0 :(得分:1)
调度动作将立即更新商店。但是,由于以下原因,React组件道具不会立即更新: