React类组件方法在函数子组件中调用报错:Cannot read property 'persons' of undefined 及State访问问题
解决React类组件方法调用与状态访问问题
我来帮你解决这两个React开发里的常见问题,咱们一个个来分析:
问题1:外部调用类组件方法时出现Cannot read property 'persons' of undefined
这个问题的核心是类组件中的普通函数方法没有正确绑定this指向。你在类里定义的removeperson和renamefun是普通函数,它们的this默认不会指向组件实例,当从子组件(函数组件)调用这些方法时,this就变成了undefined,自然访问不到this.state.persons。
解决方案(三种任选其一):
将方法改为箭头函数:
箭头函数会自动绑定当前上下文的this,直接修改类里的方法定义:removeperson = (index) => { const people=[...this.state.persons]; people.splice(index,1); this.setState({persons:people}) } renamefun = (event,id) => { const personindex=this.state.persons.findIndex(p => p.id===id); const personvalues={...this.state.persons[personindex]}; personvalues.name=event.target.value; const people=[...this.state.persons]; people[personindex]=personvalues; this.setState({persons :people}); }在构造函数中绑定
this:
如果不想改成箭头函数,可以在类的构造函数里手动绑定方法的this:constructor(props) { super(props); this.removeperson = this.removeperson.bind(this); this.renamefun = this.renamefun.bind(this); }传递方法时用箭头函数包裹:
在render里传递方法给子组件的时候,用箭头函数包裹,确保this指向组件实例:<Allpersons persons={this.state.persons} clickrename={(event, id) => this.renamefun(event, id)} clickremove={(index) => this.removeperson(index)} />
问题2:无法从关联的函数组件访问类组件的this.state.value
函数组件是独立的无状态组件(除非使用Hooks),它只能通过props接收父组件传递的数据,不能直接访问父组件的this.state。
解决方案:
把你想让函数组件访问的state值通过props传递过去。比如如果你想让Allpersons或者Person组件访问this.state.c或this.state.personview,可以这样做:
- 在App组件的
render里传递额外的props:<Allpersons persons={this.state.persons} clickrename={this.renamefun} clickremove={this.removeperson} currentCount={this.state.c} // 传递state里的c值 isPersonView={this.state.personview} // 传递personview状态 /> - 在函数组件
Allpersons里接收并使用这些props:const Allpersons=(props)=>{ // 这里就可以访问props.currentCount和props.isPersonView了 console.log(props.currentCount); return props.persons.map((person,index)=>{ return ( <div> <Person name={person.name} age={person.age } clickperson={()=>props.clickremove(index)} key={person.id} rename={(event)=>props.clickrename(event,person.id)} // 如果Person组件也需要,继续传递下去 currentCount={props.currentCount} /> </div> ) }) }
这样函数组件就能拿到父组件state里的值啦。
内容的提问来源于stack exchange,提问作者harshvardhan mehta
相关产品推荐
相关产品推荐

