gpt4 book ai didi

javascript - 从通过链接检索的数据修改 setState

转载 作者:行者123 更新时间:2023-12-02 23:25:08 24 4
gpt4 key购买 nike

大家好

我是一名年轻的编程初学者。我正在尝试从链接恢复数据到另一个组件。除了使用 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 的值只是未定义

感谢您的帮助:)

最佳答案

setState是异步方法,要在设置状态后执行某些操作,您可以将函数作为 setState

的第二个参数传递
this.setState({orderID: order_id}, () => console.log(this.state.orderId));

关于javascript - 从通过链接检索的数据修改 setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56773442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com