【问题标题】:Input state not binding onChange on first click输入状态在第一次单击时未绑定 onChange
【发布时间】:2019-05-16 02:34:50
【问题描述】:

我已经声明了一个名为 account_type 的状态。我创建了一个 onChange 事件,它在单击 div 时更改状态的值。

<div
          className="price-plan"
          value="star"
          onClick={() => this.setPlan("star")}
        >

问题是我第一次单击 div 时 account_type 状态没有更新。只有当我单击它两次时它才会更新。有没有办法通过单击 div 来更新状态。这是我的代码的摘录,显示了我正在尝试做的事情


    let isRedirect = false;

    class PricePlan extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          account_type: "",
          renderRedirect: false
        };

        this.handleChange = this.handleChange.bind(this);
      }

      // Handle fields change
      handleChange = input => e => {
        this.setState({ [input]: e.target.value });
      };


      setPlan(plan) {
        this.setState({
          account_type: plan
        });
        console.log(this.state.account_type);
        // if (this.state.account_type !== undefined) {
        //   isRedirect = true;
        // }
      }

      render() {
        if (isRedirect) {
          return (
            <Redirect
              to={{
                pathname: "/sign-up",
                state: { step: 2, account_type: this.state.account_type }
              }}
            />
          );
        }

        return (
            <div
              className="price-plan"
              value="star"
              onClick={() => this.setPlan("star")}
            >
              <h3>{this.props.planName}</h3>
              <div className="mute price-row">Name</div>
              <p className="price">Price</p>
              <span className="billed-frequency">Cycle</span>
            </div>

        );
      }
    }

【问题讨论】:

  • setState异步的,所以当你console.log它时它不会在下一行改变

标签: javascript reactjs events onchange


【解决方案1】:

正如@Jayce444 建议的那样,setState 不会立即更新state。所以setPlan 应该是这样的

setPlan(plan) {
    this.setState({
         account_type: plan
    });
    console.log(plan);  // Don't expect immediate state change in event handler
  }

但是您可以在render() 函数中的任何位置使用this.state.account_type。并且在第一次点击时更新this.state.account_type 后会进行渲染。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多