React中setState设置状态后回调内fetchCryptoStats未调用如何解决
问题解决建议
核心问题为setState回调函数的this指向丢失,普通匿名函数的this不绑定当前组件实例,导致this.fetchCryptoStats无法正常调用,可通过以下方案解决:
- 方案1:将
setState回调替换为箭头函数,自动继承外层作用域的this指向
<ListItem bottomDivider={true} onPress={() => { this.setState( { setModalVisible: true, selectedItem: symbol.toUpperCase(), }, () => { console.log(this.state.selectedItem); this.fetchCryptoStats(this.state.selectedItem); }, ); }}>
- 方案2:提前保存当前组件的
this指向到临时变量,回调内通过临时变量调用方法
<ListItem bottomDivider={true} onPress={() => { const _this = this; this.setState( { setModalVisible: true, selectedItem: symbol.toUpperCase(), }, function () { console.log(_this.state.selectedItem); _this.fetchCryptoStats(_this.state.selectedItem); }, ); }}>
- 方案3:确认
fetchCryptoStats方法本身已绑定组件this,可在构造函数中绑定或直接定义为类箭头函数
// 构造函数绑定示例 constructor(props) { super(props); this.state = { setModalVisible: false, selectedItem: '' }; // 绑定方法this指向 this.fetchCryptoStats = this.fetchCryptoStats.bind(this); } // 类箭头函数定义示例 fetchCryptoStats = (selectedItem) => { // 方法内部逻辑 }
额外排查点
如果修改后回调仍未执行,先确认回调内的console.log是否能正常输出selectedItem的值,若可以正常输出但方法未触发,排查fetchCryptoStats内部是否有报错中断了执行流程。
内容的提问来源于stack exchange,提问作者Frank Boccia
相关产品推荐
相关产品推荐

