如何从.Map函数Re​​act内部更改状态

时间:2018-07-08 16:48:47

标签: javascript reactjs scope this

我有此功能

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)

在render react函数/方法内部正在调用renderEitherMenuOrCompanyList函数。

我的问题是我无法通过renderCompanies .map函数设置状态。我不断收到“无法读取未定义的属性'setState'”。这应该很简单,但我无法做到

2 个答案:

答案 0 :(得分:0)

确保给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>
  );
})}

答案 1 :(得分:0)

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

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

您还将参数命名为onClick item,但这实际上是click事件。您需要item函数已经定义的map。将参数命名为onClick,以其他方式命名,否则不要使用任何名称,以避免覆盖您实际需要的item变量。

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