【问题标题】:How to change State from inside .Map function React如何从 .Map 函数 React 内部更改状态
【发布时间】:2018-07-08 16:48:46
【问题描述】:

我有这个功能

renderCompanies() {
    if (this.props.companies)
      return [
        <div>
          Dashboard hello <div>{this.renderProfile()}</div>
          <div>
            {this.props.companies.map(function(item, i) {
              return (
                <div>
                  <div
                    key={i}
                    onClick={item => {
                      this.setState({ currentCompany: item });
                    }}
                  >
                    {i}: {item.name}
                  </div>

                  <button>Delete Company</button>
                </div>
              );
            })}
          </div>
          <AddCompanyPopUp />
        </div>
      ];
  }

我想遍历 this.props.companies 并呈现一个项目列表。我希望用户能够单击特定项目并将该项目保存到状态。

这个函数在另一个函数中运行

renderEitherMenuOrCompanyList() {
    if (this.state.currentCompany) {
      return <Menu companies={this.state.currentCompany} />;
    } else {
      return <div>{this.renderCompanies()}</div>;
    }
  }

两者都已经绑定到这个

this.renderCompanies = this.renderCompanies.bind(this);
this.renderProfile = this.renderProfile.bind(this);
this.renderEitherMenuOrCompanyList = this.renderEitherMenuOrCompanyList.bind(this)

正在渲染反应函数/方法中调用 renderEitherMenuOrCompanyList 函数。

我的问题是我无法从 renderCompanies .map 函数中设置状态。我不断收到 "Cannot read property 'setState' of undefined" 。这应该很简单,但我一直做不到

【问题讨论】:

    标签: javascript reactjs scope this


    【解决方案1】:

    确保给map 的函数也被绑定,或者是一个箭头函数:

    {this.props.companies.map((item, i) => {
      return (
        <div>
          <div
            key={i}
            onClick={() => {
              this.setState({ currentCompany: item });
            }}
          >
            {i}: {item.name}
          </div>
    
          <button>Delete Company</button>
        </div>
      );
    })}
    

    【讨论】:

    • 但它已经是箭头函数了? onClick={item => { this.setState({ currentCompany: item }); }}
    • @DavidMbwana 不是map 的实际功能。将您的代码 this.props.companies.map(function(item, i) { ... } 与我的答案进行比较。
    • 有效。太好了!!
    【解决方案2】:

    传递给this.props.companies.map 的函数不是箭头函数,因此它创建了一个新的this。将其更改为箭头函数以从外部保留this。

    this.props.companies.map( ( item, i ) => { ... } )
    

    您还将参数命名为 onClick item,但它实际上是点击事件。您希望 item 已经由 map 函数定义。将参数命名为 onClick 其他名称,或不命名,以避免覆盖您实际需要的 item 变量。

    onClick={ () => { ... } }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-24
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多