React组件传递state与setState后状态无法更新问题求助
解决React类组件传递方法时的
this指向问题 嘿,我完全懂你遇到的困扰——这是React类组件里非常常见的this绑定问题,刚学React的时候很容易踩这个坑!
问题根源
你注释掉的代码能正常运行,是因为在render里用箭头函数调用this.showAge()时,箭头函数会自动捕获当前render上下文的this,指向的是Pages组件实例,所以能顺利调用this.setState。
但当你直接把this.showAge作为props传给Page1组件时,这个方法的this指向就丢失了。当子组件调用props.showAge()时,this会变成undefined(严格模式下),自然就会报错“Cannot read property 'setState' of undefined”。
三种可行的解决方案
方案1:在构造函数中绑定this
修改Pages.js,添加构造函数并绑定方法:
import React, { Component } from 'react'; import Page1 from './page1'; import './Pages.css'; class Pages extends Component { constructor(props) { super(props); this.state = { age: "joe" }; // 绑定this到showAge方法 this.showAge = this.showAge.bind(this); } showAge() { this.setState({ age: "25" }); } render() { return ( <div> <Page1 age={this.state.age} showAge={this.showAge} /> </div> ); } } export default Pages;
方案2:用箭头函数定义类方法(最简洁)
直接把showAge定义为类的箭头函数属性,这样this会自动绑定到组件实例:
import React, { Component } from 'react'; import Page1 from './page1'; import './Pages.css'; class Pages extends Component { state = { age: "joe" } // 箭头函数自动绑定this showAge = () => { this.setState({ age: "25" }); } render() { return ( <div> <Page1 age={this.state.age} showAge={this.showAge} /> </div> ); } } export default Pages;
方案3:传递props时用箭头函数包裹
在传递showAge的时候,用箭头函数包裹一次,确保this指向正确:
import React, { Component } from 'react'; import Page1 from './page1'; import './Pages.css'; class Pages extends Component { state = { age: "joe" } showAge() { this.setState({ age: "25" }); } render() { return ( <div> {/* 用箭头函数包裹,确保this指向组件实例 */} <Page1 age={this.state.age} showAge={() => this.showAge()} /> </div> ); } } export default Pages;
验证效果
修改后,点击Page1组件里的“Click to show age”标题,就能正常更新状态,显示25了。
内容的提问来源于stack exchange,提问作者chree
相关产品推荐
相关产品推荐

