【问题标题】:in react can't get new value after immediately setState在立即 setState 后反应无法获得新值
【发布时间】:2016-03-21 05:57:33
【问题描述】:

我正在使用 Reactjs。如果输入不正确,我将在其中设置错误。
示例代码为:

handleChange: function() {
 if(shares) {
   this.setState({
     error_shares:''
   })
 } 
 if(this.state.error_shares === ''){
  console.log('entered!!')
 }
}

此处error_state 的值不会反映下一个 if 中的更改值

【问题讨论】:

  • setState 是异步操作。不过,您可能不需要这样做,对吧?
  • 是的。但不能立即工作,为此你需要反应链接状态混合。但仍然无法正常工作
  • 当然..我的意思是在您发布的代码中您可以检查shares 是否为真以知道它是否为空字符串,所以也许您没有发布您的实际代码有问题。
  • 您也可以将回调作为setState 方法的第二个参数传递。它会在状态实际改变后被调用。

标签: reactjs


【解决方案1】:

是的,这是期望的行为。

值没有更新的原因是你的组件还没有重新渲染。

如果你需要这样的功能,你应该使用componentDidUpdate回调。

查看生命周期方法here

解释

这是 React 的工作原理:

  1. 每个组件都是external props + internal state的函数

  2. 如果两者中的任何一个被触发,组件就会排队等待重新渲染(它是异步的,因此客户端应用程序不会被阻塞)。

  3. 有关操作的确切顺序,请参见上面的链接,但这里有一些概念证明。

    import React from 'react';
    
    class Example extends React.Component {
    
        constructor(props, context) {
            super(props, context);
            // initial state
            this.state = {
                clicked: false
            };
        }
    
        componentDidUpdate(prevProps, prevState) {
            console.log(this.state.clicked);   // this will show "true"
        }
    
        render() {
            return (
                <button 
                    onClick={() => {
                        this.setState({clicked: true}); 
                    }}
                >
                </button>
            );
        }
     }
    

【讨论】:

  • 你能给我详细解释一下吗?你给了我希望
【解决方案2】:

setState 本质上是异步的。

第二个(可选)参数是一个回调函数,它将被 在 setState 完成并重新渲染组件后执行。

所以你可以做这样的事情。

handleChange: function () {
    if ( shares ) {
        this.setState( {
            error_shares: ''
        }, function () {
            if ( this.state.error_shares === '' ) {
                console.log( 'entered!!' )
            }
        } )
    }
}

来源:https://facebook.github.io/react/docs/component-api.html#setstate

【讨论】:

    【解决方案3】:

    是的,确实。

    setState() 不会立即改变 this.state 而是创建一个挂起的状态转换。调用此方法后访问 this.state 可能会返回现有值。

    http://facebook.github.io/react/docs/component-api.html

    【讨论】:

    • 那么解决办法是什么?
    【解决方案4】:

    没有。在 setState 之后,您无法在控制台中获取更新值。这是因为一旦调用 setState,视图就会重新渲染。因此,要获取更新的值,您可以在 render() . 中检查它

    render(){
     if(this.state.error_shares === ''){
        //your code.
     }
    }
    

    【讨论】:

    • 实际上我调用的是 api 而不是 console 我希望这个序列无论如何都能执行
    • 你的方法是错误的。你为什么要触发 setState 而不是调用你的 api。在 api 响应后,您将需要调用 setState。使用事件处理它。
    猜你喜欢
    • 2021-09-10
    • 1970-01-01
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多