【问题标题】:React component doesn't have access to new state values unless the method updating the state is run twice除非更新状态的方法运行两次,否则 React 组件无法访问新的状态值
【发布时间】:2019-05-01 19:51:53
【问题描述】:

我遇到了这种奇怪的行为,我的 onClick 方法 handleClick 必须运行两次才能使 CardView 组件能够访问新状态。我想这可能意味着在更新状态时,组件仍在引用 groupedCardInfo 属性的旧状态值?

这是流程,希望能深入了解我哪里出错了:

GroupedRowContainer:

<p onClick={() => { this.props.handleClick(this.props.properties) }}>{this.props.parentName}</p>

然后这会在App.js 中调用以下方法:

  handleClick(properties){
    console.log("toggle click!")
    // this.setState({active : !this.state.active});

    this.setState({
      active: !this.state.active,
      groupedCardInfo: properties
    })
  }

应该更新App.js 中的以下状态属性:

  constructor(props) {
    super(props);
    this.state = {
      genInfoList: [],
      groupedObjectsList: [],
      // This obj stores data for cases where there's only one property
      cardInfo: {
        name: data[0].name,
        type: data[0].dataType,
        usage: data[0].app_keys
      },
      data: [],
      active: false,
      // This obj stores data in cases where there are multiple properties to render in the pane
      groupedCardInfo: [{
        name: "placeholder name"
      }]
    };
    this.changeInfoList = this.changeInfoList.bind(this)
    this.handleClick = this.handleClick.bind(this)
  }

占位符被替换为properties 对象。这个 prop 被传递给需要它的 CardView 组件,就像在 App.js 中一样:

<CardView name = {this.state.cardInfo.name} type = {this.state.cardInfo.type} usage = {this.state.cardInfo.usage} groupedCardInfo = {this.state.groupedCardInfo}/>

为什么CardViewhandleClick方法运行两次时才渲染更新的groupedCardInfo

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    看起来您将active 设置为!this.state.active,您没有将默认状态设置为活动。您需要为您的状态设置初始值。

    【讨论】:

    • 我确实给了它一个默认值,我只是没有在最初的帖子中包含它。编辑它以包括现在:)
    【解决方案2】:

    请尝试使用箭头函数更新状态

    handleClick(properties) {
        console.log("toggle click!")
        this.setState(state => ({
            ...state,
            active: !state.active,
            groupedCardInfo: properties
        }))
    

    }

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 2023-02-11
      • 2022-01-22
      • 1970-01-01
      • 2018-05-01
      • 1970-01-01
      • 2019-08-30
      相关资源
      最近更新 更多