【问题标题】:Cannot read property 'concat' of undefined React JS无法读取未定义 React JS 的属性“concat”
【发布时间】:2018-09-06 16:26:09
【问题描述】:

尝试在此组件的状态下将对象添加到数组中,无法将新对象连接到数组而没有“属性未定义”错误。

我已经能够让它在带有数组的“浅”状态下工作,但我希望它能够在内部单独的数组中工作。

国家

    constructor(props) {
      super(props);
        this.state = {
          show: false,
          id: null,
          name: 'New Task',
          timerOn: false,
          seconds: 0,
          minutes:0,
          hours:0,
          complete: {
            todayId: null,
            list: []
          }
        }
      }

更新状态的方法,制作“控件”(分钟、秒、开始等)的副本,将状态重置为初始值,获取状态副本并将其应用于数组:

    completeTaskHandler = () => {
      if (this.state.seconds === 0 && this.state.minutes === 0 && this.state.hours === 0) {
        alert('Please Provide a name');
      }
      else {
        const end = new Date();
        let finishedTask = new Object ({
          start: this.state.id,
          end: end,
          name: this.state.name,
          seconds: this.state.seconds,
          minutes: this.state.minutes,
          hours: this.state.hours,});

        this.setState((prevState,props) => {
          return {
            start: null,
            show: false,
            id: null,
            name: 'task',
            timerOn: false,
            seconds: 0,
            minutes:0,
            hours:0,
            complete: prevState.complete.list.concat(finishedTask)
          }
        });
        clearInterval(this.interval);
      }
    }

【问题讨论】:

  • 您能否提供更清晰的帮助?
  • 尝试记录 'prevState.complete.list' 并查看它是否是您期望的对象(数组)
  • 因为列表是一个数组。更改为完成:[...prevState.complete.list, finishedTask]

标签: javascript reactjs react-state-management


【解决方案1】:

您正在对数组进行 concat。由于 list 是一个数组。

使用先前的状态将新值推送到数组。检查以下解决方案以更好地理解

  this.setState((prevState,props) => {
      return {
        start: null,
        show: false,
        id: null,
        name: 'task',
        timerOn: false,
        seconds: 0,
        minutes:0,
        hours:0,
        complete: [...prevState.complete.list, finishedTask]
      }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 2016-08-06
    • 2022-11-17
    • 2020-12-24
    • 2020-08-21
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多