你能告诉我为什么不在 React 中获取更新的 props 值吗?
这是我的代码 https://stackblitz.com/edit/react-redux-basic-counter-1e8gdh?file=shared/components/NavBar.js
在我的示例中,我有一个按钮 -
。单击它会减少值。我发送的操作值是 decremented
但我没有得到 updated value
handle=()=>{
this.props.decrement();
this.getCount();
}
getCount=()=>{
const {counter}= this.props;
console.log(counter);
}
查看我的console.log
预期输出是-1
当前输出为0
为什么?当我点击 -
按钮时显示输出
最佳答案
原因是在控制台打印值时 Prop 没有更新。当 Prop 更新时, react 组件重新渲染并显示计数器值。检查您是否可以使用 setTimeout
。
handle=()=>{
this.props.decrement();
setTimeout(this.getCount,10)
}
如果你想控制台记录你的生命周期的值(value)。 你可以使用 componentDidUpdate
componentDidUpdate(prevProps) {
if (this.props.counter !== prevProps.counter) {
console.log(this.props.counter);
}
}
或 componentWillReceiveProps(对于 React 版本 < 16)
componentWillReceiveProps(newProps) {
if( newProps.counter != this.props.counter ) {
console.log(newProps.counter);
}
}
或者 getDerivedStateFromProps( react 版本 16 +)
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.counter !== prevState.counter ) {
console.log(nextProps.counter);
}
}
关于javascript - 为什么我没有在 react 中获得更新的 Prop 值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55661821/