This question already has answers here:
setState doesn't update the state immediately
                            
                                (14个回答)
                            
                    
                    
                        React slow setState at console.log
                            
                                (1个答案)
                            
                    
                在11个月前关闭。
        

    

大家好

我是编程的年轻初学者。我正在尝试从链接到另一个组件恢复数据。除了将恢复的数据放在带有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));

10-07 14:00
查看更多