React子组件通过callback修改父组件state报this.setState is not a function如何解决
报错原因
this.setState is not a function报错的根源是this指向问题:父组件中定义的onAdd是普通函数,作为prop传递给子组件后,子组件调用时函数内部的this已经丢失了父组件实例的指向,因此无法调用setState方法。
修复方案(两种写法二选一即可)
- 写法1:在父组件构造函数中手动绑定this
在父组件constructor中新增绑定逻辑:
constructor(props){ super(props) this.state = { add: false }; // 新增this绑定 this.onAdd = this.onAdd.bind(this) }
- 写法2:将父组件的
onAdd改为箭头函数,自动继承外层this
// 把原有的onAdd方法改为箭头函数写法 onAdd = () => { this.setState({add : false}); }
表单自动隐藏逻辑实现
父组件本身已经实现了this.state.add为true时才渲染AddForm的判断,只要onAdd方法正常执行将add改为false,表单就会自动隐藏。需要修正子组件的接口请求逻辑,确保请求成功后再触发回调:
async add(){ // 接收接口返回值 const response = await POST("https://localhost:5001/Elements/Add", Element.element); // 请求成功后再触发父组件回调隐藏表单 if(response.data === true){ this.props.callback(); } }
完整修正后代码
父组件代码
class Folder extends React.Component { constructor(props){ super(props) this.state = { add: false }; this.onAdd = this.onAdd.bind(this) } onAdd(){ this.setState({add : false}); } render() { return ( <div className={styles.folder} > {/* 原有触发add为true的按钮逻辑保留即可 */} {this.state.add ? <AddForm callback={this.onAdd}/> : ""} </div> ); } }
子组件代码
class AddForm extends React.Component{ constructor(props) { super(props); this.state = {checked : false}; } async add(){ const response = await POST("https://localhost:5001/Elements/Add", Element.element); if(response.data === true){ this.props.callback(); } } render() { return ( <div className={styles.add_form}> <button className={styles.add_form_btn} onClick={this.add.bind(this)}>Add</button> </div> ); } }
内容的提问来源于stack exchange,提问作者Mariusz Szczerba
相关产品推荐
相关产品推荐

