React遍历数组渲染多按钮绑定点击事件报错:Cannot read property 'props' of undefined
React聊天机器人按钮点击事件报错:Cannot read property 'props' of undefined
嗨,我看到你在开发React聊天机器人时遇到了这个常见的上下文问题,别担心,咱们一步步来解决它!
核心错误原因
你在ChatInput组件的map方法里使用了普通的function(item, i)作为回调函数,这会导致函数内部的this失去指向组件实例的上下文,所以当你尝试访问this.props时,自然就会得到undefined,触发报错。
解决方案
这里有两种简单的修复方式:
1. 使用箭头函数作为map回调
箭头函数会自动继承外部作用域的this,完美解决上下文丢失的问题:
// 修改ChatInput组件里的map部分 {this.props.myButtonProp.map((item, i) => { return( <Button key={i} // 记得加key属性,避免React警告 buttonProp={item.text} buttonOnClick={this.props.onClickProp} /> ) })}
2. 给普通回调函数绑定this
如果你更习惯用普通函数,可以在回调末尾通过.bind(this)强制绑定组件的上下文:
{this.props.myButtonProp.map(function(item, i){ return( <Button key={i} buttonProp={item.text} buttonOnClick={this.props.onClickProp} /> ) }.bind(this))}
额外需要修复的潜在问题
除了上面的核心错误,你的ChatWindow组件里还有一个容易踩坑的地方:
- 你在
socket.on的回调里用了普通函数,而且addMessage的定义位置可能导致this无法正确指向组件实例,进而无法调用this.setState。 - 多次调用
this.setState可以合并成一次,提升性能。
修改后的ChatWindow构造函数部分:
constructor(props){ super(props); this.state = { email: '', message: '', time: '', buttonShow: false, buttons: [], messages: [], buttonSelection: '' } this.socket = io('http://localhost:8080') // 先定义addMessage,用箭头函数确保this指向组件 const addMessage = data => { console.log(data); // 合并setState调用 this.setState({ messages: [...this.state.messages, data.message], buttonShow: data.buttonShow, buttons: data.buttons }); console.log(this.state); }; // socket回调用箭头函数,保证能正确调用addMessage this.socket.on('RECEIVE_MESSAGE', (data) => { addMessage(data); }); this.sendButtonSelection = e => { this.setState({buttonSelection: e.target.value}); console.log(e.target.value); }; };
小细节优化
- React里要使用
className代替class,你代码里的<div class="panel-footer">要改成<div className="panel-footer">。 - 所有列表渲染的元素都要加上唯一的
key属性,这是React的要求,能避免不必要的重渲染和警告。
内容的提问来源于stack exchange,提问作者trurohit
相关产品推荐
相关产品推荐

