javascript - 如何访问 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”
解决方案
由于您的代码位于地图的回调函数中,因此 (this)context 将被称为回调函数的 this。
在其他地方,它在渲染函数中,并且 (this)context 正确地引用了组件 this。
将下面的行放在渲染函数中
const self = this;
然后参考self .switchHandler where this.switchHandler not working 如下
clickChild={self.switchHandler}
谢谢
推荐阅读
- powerbi - 要添加到 Power BI 报表的动态超链接
- python - Python 3.9.7 - if 语句返回 true 时如何继续执行函数?
- mongodb - Spring-data MongoDB 等效查询
- tags - 如何拆分标签和范围以插入/删除标签?
- git - 如何判断哪个 GIT 孩子是新分支?
- javascript - 访问iframe的innerHTML
- vb.net - 用子类更新了一个类,它没有出现在其他类中
- javascript - discord.js SyntaxError:意外的令牌?
- python - tkinter 小部件操作
- python - Django M2M / 1 Django Admin Inline 中与 SELF 的多对多关系