[英]Why can't I access updated redux data in componentDidMount without timeout?
I am setting redux state in my componentDidMount function and then trying to access immediately and am not able to. 我在我的componentDidMount函数中设置了redux状态,然后尝试立即访问而无法访问。 I've stripped out some unnecessary complexity, but here's the basic setup:
我去除了一些不必要的复杂性,但这是基本设置:
// URL page?id=1
componentDidMount() {
this.props.setFilter({ location: this.props.location.search.id) });
console.log('in mount', this.props.filter);
}
// Action
export function setFilter(filterData) {
return {
type: SET_FILTERS,
payload: filterData
};
}
// Reducer
export default function(state = INITIAL_STATE, action = {}) {
switch(action.type) {
case SET_FILTERS: {
const newState = { ...state, filter: action.payload };
console.log('reducer state', newState);
return newState;
}
...
}
This will output 这将输出
reducer state { location: 1 }
in mount {}
but if I change the componentDidMount to 但是如果我将componentDidMount更改为
componentDidMount() {
this.props.setFilter({ location: 1 });
setTimeout(() => { console.log(this.props.filter), 0; });
}
it works as expected and outputs 它按预期工作并输出
reducer state { location: 1 }
in mount { location: 1 }
Why would this be? 为什么会这样呢?
Thanks! 谢谢!
this.props
is not updated directly by setFilter
. setFilter
不会直接更新this.props
。
The action dispatched to the store triggers mapStateToProps
to re-run, collect the new value, and merge it into the component props. 分派到商店的动作将触发
mapStateToProps
重新运行,收集新值并将其合并到组件props中。
console.log('in mount', this.props.filter);
runs before this cycle is complete. 在此循环完成之前运行。
setTimeout(() => { console.log(this.props.filter), 0; });
runs after this cycle is complete. 在此循环完成后运行。
try this.. 尝试这个..
componentDidMount() {
const propsCopy = this.props;
this.props.setFilter({ location: 1 });
console.log("before", this.props === propsCopy);
setTimeout(() => { console.log("after", this.props === propsCopy) }, 0);
}
you'll get before true
& after false
. 您将
before true
和after false
得到。
so although the dispatch is synchronous, the props objects before and after the setTimout are different, and it's only the new props that have the filter set. 因此,尽管调度是同步的,但setTimout之前和之后的props对象是不同的,只有新的props才设置了过滤器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.