【发布时间】:2019-11-08 10:29:22
【问题描述】:
大家好
我是一名年轻的编程初学者。我正在尝试将数据从链接恢复到另一个组件。除了将这些恢复的数据放入带有 setState 的状态对象之外,一切正常。我想我对 setState 一无所知,但我很迷茫。
我有这个发送数据“Command_ID”的链接:
<Link to={`/produits/${Command_ID}`} className="item" params={{ Command_ID: {Command_ID}}}>
正如预期的那样,我恢复了这样的数据,我记得它是“order_id”:
state = {orderId: null};
componentDidMount() {
const order_id = this.props.match.params;
console.log(order_id);
this.setState({orderID: order_id});
console.log(this.state.orderID);
}
我可以在我的 console.log(order_id) 中看到正确的数字在具有良好“Command_ID”的链接部分中恢复。但是当我尝试将它与 setState 一起使用并在控制台中查看它是否有效时,我的 this.state.orderID 的值为 undefined
感谢您的帮助:)
【问题讨论】:
-
未定义或为空?
-
setState是异步的。您拥有的代码可以执行您想要的操作,但是第二个 console.log 命令运行得太早而无法显示更改。你可以把它放在一个回调中:this.setState({ orderID: order_id }, function () { console.log(this.state.orderID); });(该函数将在状态改变后运行) -
未定义。好的,所以你认为我必须先验证一下这个值吗?因为这是我第一次遇到这个问题
-
这不是我们“认为”的,这绝对是正在发生的事情。 reactjs.org/docs/react-component.html#setstate 引用:
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall.
标签: javascript reactjs hyperlink components setstate