首页 > 解决方案 > 如何访问 this.state.map() 中的类函数

问题描述

我正在尝试在内部使用 switchHandler 函数this.state.persons.map()但得到

“无法读取未定义的属性‘switchHandler’”错误

. 但是,如果我在地图功能之外使用它,它是可以访问的。

class App extends Component {
  state = {
    persons: [
      { name: "Max", age: 28 },
      { name: "Manu", age: 27, child: "My hobbies : racing" },
      { name: "Ron", age: 26 }
    ]
  };

  switchHandler = () => {
    this.setState({
      persons: [
        { name: "Maxii", age: 28 },
        { name: "Manu", age: 27, child: "My hobbies : swiming" },
        { name: "Ron", age: 26 }
      ]
    });
    //return "correct";
  };
  render() {
    //let obj = new App();
    return (
      <div className="App">
        <button onClick={this.switchHandler}>Switch Name</button>
        {this.state.persons.map(function(data) {
          return (
            <div>
              <Person
                clickChild={this.switchHandler}
                name={data.name}
                age={data.age}
              >
                {data.child}
              </Person> // // Here I'm getting error for switchHandler

            </div>
          );
        })}
        <Person name="tag" age="34" clickChild={this.switchHandler}>
          just
        </Person> // Here switchHandler is working fine


      </div>
    );
  }
}

export default App;

错误:

App.js:34 未捕获的类型错误:无法读取未定义的属性“switchHandler”

标签: javascript

解决方案


由于您的代码位于地图的回调函数中,因此 (this)context 将被称为回调函数的 this。

在其他地方,它在渲染函数中,并且 (this)context 正确地引用了组件 this。

将下面的行放在渲染函数中

const self = this;

然后参考self .switchHandler where this.switchHandler not working 如下

clickChild={self.switchHandler}

谢谢


推荐阅读