【问题标题】:ReactJS Uncaught TypeError: Cannot read property 'concat' of undefinedReactJS Uncaught TypeError:无法读取未定义的属性“concat”
【发布时间】:2017-07-20 02:57:53
【问题描述】:

我想在每次按下提交按钮时将一个元素添加到状态中。问题是,每次我按下提交按钮,它都会返回

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 状态?

【问题讨论】:

    标签: arrays reactjs


    【解决方案1】:

    这一行:

    rooms: this.state.notes.concat(e)

    您还没有在任何地方定义notes,因此它说它不能在undefined 上执行concat

    【讨论】:

      猜你喜欢
      • 2016-11-24
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 2020-03-28
      • 2023-04-11
      相关资源
      最近更新 更多