![](/img/trans.png)
[英]TypeError: Cannot read property 'map' of undefined is showing when I'm trying to map over the props passed from parent component to child component
[英]Getting error of "Cannot read props of undefined" when being passed to child component for onChange method
将 onchange 函数传递给子组件时,我收到“无法读取未定义的道具”的错误,但是,当控制台记录道具时,会显示正确的属性。
我以前这样做过,我将一个 onClick 道具传递给了一个子按钮,这似乎工作得很好。
错误消息仅在尝试编辑字段时发生。
父组件
//Parent component onChange = e => { e.preventDefault(); console.log(e); } render(){ return( <div className="App"> <div className="cardRow"> <Card question={this.state.currentCard.question} answer={this.state.currentCard.answer} source={this.state.currentCard.source} onClick={this.submitUpdate.bind(this)} recordChange={this.onChange.bind(this)}>{this.state.update}</Card> ..... //child component class Card extends Component { //the below code is where the error message is pointing recordChange(){ this.props.recordChange(); } onSubmit(){ this.props.onSubmit(); } render(props){ console.log(this.props); return( <div className="card-container"> {this.props.children? <div className="cardUpdate"> <form className="update-form"> <h5>Front</h5> <input type="text" value={this.props.question} onChange={this.recordChange}/> <h5>Answer</h5> <textarea type="text" value={this.props.answer} onChange={this.recordChange}/> <h5>Source</h5> <input type="text" value={this.props.source} onChange={this.recordChange}/> <div> <button onClick={this.props.onClick}>Submit</button> </div> </form> </div> : <div className="card"> <div className="front"> <div className="question">{this.props.question}</div> </div> <div className="back"> <div className="answer">{this.props.answer}</div> <div className="source">{this.props.source}</div> </div> </div> } </div> ); }
recordChange
在类的上下文中无权访问this
。
recordChange() {
// 'this' is undefined.
this.props.recordChange();
}
然而,正如你所注意到的, console.log(this.props);
内部render
工作正常。 这是因为render
在类的上下文中被调用; 而recordChange
不是。
它变成一个箭头的功能,使this
在范围:
recordChange = () => {
this.props.recordChange();
}
或者在构造函数中将其绑定到this
:
constructor(props) {
super(props);
this.recordChange = this.recordChange.bind(this);
}
recordChange(){
this.props.recordChange();
}
或者更好:
根本不要使用子函数。 如果它所做的只是从props
调用函数,则没有必要。 只需执行onChange={this.props.recordChange}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.