我想在每次按下提交按钮时将元素添加到状态。问题是,每次按下提交按钮,它都会返回
Uncaught TypeError: Cannot read property 'concat' of undefined
错误,我无法弄清楚为什么它未定义。
class ChatRoom extends React.Component{
constructor(props){
super(props);
this.state = {
rooms: ['room1', 'room2'],
chatRoom: ''
}
}
handleAddRoom = (e) => {
console.log('handleAddRoom', e);
this.setState({
rooms: this.state.notes.concat(e)
})
}
handleSubmit(){
var newRoom = ReactDOM.findDOMNode(this.refs.room).value;
console.log(newRoom);
ReactDOM.findDOMNode(this.refs.room).value = '';
this.handleAddRoom(newRoom);
}
render(){
console.log("rooms: ", this.state.rooms)
return(
<div>
Hello from chat room!! Please enter new room:
<input type="text" className="form-control" placeholder="Add a new note" ref="room" />
<span className="input-group-btn">
<button className="btn btn-default" type="button" onClick={this.handleSubmit.bind(this)}>Submit</button>
</span>
</div>
)
}
}
这是给我带来问题的组件。我将console log
放在不同的位置,它们都返回正确的值。不知何故,当它试图连接JS时,它说它是undefined
值。如何将元素连接到rooms
状态?
答案 0 :(得分:2)
这一行:
rooms: this.state.notes.concat(e)
您尚未在任何地方定义notes
,因此它表示无法在concat
上执行undefined
。