Javascript 为什么我在react中没有更新道具的价值
你能告诉我为什么不在react中更新道具的价值吗 这是我的密码 在我的示例中,我有一个按钮Javascript 为什么我在react中没有更新道具的价值,javascript,reactjs,redux,react-redux,Javascript,Reactjs,Redux,React Redux,你能告诉我为什么不在react中更新道具的价值吗 这是我的密码 在我的示例中,我有一个按钮-。单击它可以减小值。我调度的动作值是递减的,但我没有得到更新的值 handle=()=>{ this.props.decrement(); this.getCount(); } getCount=()=>{ const {counter}= this.props; console.log(counter); } 请参阅我的控制台。日志 预期输
-
。单击它可以减小值。我调度的动作值是递减的
,但我没有得到更新的值
handle=()=>{
this.props.decrement();
this.getCount();
}
getCount=()=>{
const {counter}= this.props;
console.log(counter);
}
请参阅我的控制台。日志
预期输出为-1
当前输出为0
为什么??当我点击
-
按钮时,它显示输出,原因是在控制台中打印值时,道具未更新。道具更新后,react组件将重新渲染并显示计数器值。要检查是否可以使用设置超时
handle=()=>{
this.props.decrement();
setTimeout(this.getCount,10)
}
如果希望控制台记录该值,则可以更改生命周期。
您可以使用componentDidUpdate
componentDidUpdate(prevProps) {
if (this.props.counter !== prevProps.counter) {
console.log(this.props.counter);
}
}
或组件将接收道具(对于react版本<16)
或者从Props获取DerivedStateFromProps(react版本16+)
对我想公布我的答案。但是您首先创建了
prevState。计数器未定义中没有计数器state@user944513你使用了什么生命周期?根据您的示例,您应该使用componentWillReceiveProps()@TRomesh。您可以查看并更新您的答案吗
componentWillReceiveProps(newProps) {
if( newProps.counter != this.props.counter ) {
console.log(newProps.counter);
}
}
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.counter !== prevState.counter ) {
console.log(nextProps.counter);
}
}