【问题标题】:Cannot read property 'columns' of undefined无法读取未定义的属性“列”
【发布时间】:2020-10-31 12:42:02
【问题描述】:

我正在尝试从服务器和地图读取 json 数据。当我手动输入相同的数据作为代码列表时。有用。但是当我试图从服务器读取数据时它不起作用。我知道问题出在地图上,但我想不通。可能是什么问题?这是代码和 json 数据。谢谢

 class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      boards: {
        id: null,
        name: null,
        owner: null,
        columns:[]
      }
    };
  }

  getBoard() {
    fetch("http://localhost:3001/boards/2")
      .then(res => res.json())
      .then(list => console.log(list))
      .then(list => this.setState({boards: list}));
  }

  componentWillMount() {
    this.getBoard();
  }
     {this.state.boards.columns.map((column, columnIndex) => (<Column
            status={this.state.addModalShow}
            onModalShow={this.onModalShow}
            onHide={addModalClose}
            addCard={this.addTask}
            column={column}
            columnIndex={columnIndex}
            key={columnIndex}
            onMoveLeft={cardIndex => this.handleMove(columnIndex, cardIndex, DIRECTION_LEFT)}
            onMoveRight={cardIndex => this.handleMove(columnIndex, cardIndex, DIRECTION_RIGHT)}
            onAddCard={() => this.handleAdd(columnIndex)}
            deleteColumn={() => this.deleteColumn(columnIndex)}
            addColumn={() => this.handleAdd()}
            deleteTask={cardIndex => this.deleteTask(columnIndex, cardIndex)}/>))}
        {
          id: 2,
          name: "Board3",
          owner: "Ali",
          -columns: [
            -{
              id: 5,
              name: "eee",
              cards: [
                -{
                  id: 5,
                  name: "TestA",
                  description: "Desc",
                  link: "google.com",
                  deadline: "2013-04-06"
                }, 
               -{
                  id: 8,
                  name: "testB",
                  description: "Desc",
                  link: "google.com",
                  deadline: null
                }
              ]
            }, 
           -{
              id: 6,
              name: "ff",
              cards: []
            }
          ]
      }

【问题讨论】:

  • 你确定你的状态正在设置吗?根据文档reactjs.org/docs/react-component.html#mounting,还使用 ​​componentDidMount() 而不是 componentWillMount
  • 是的,我打印列表,它显示在控制台中
  • 正确格式化代码
  • 我使用了 componentDidMount() 没有任何改变。我猜问题出在映射中
  • 是的代码在渲染方法中。好的,我会修复

标签: javascript node.js json reactjs mapping


【解决方案1】:

但是您不会在将响应打印到控制台的函数内返回任何内容。请阅读 Promise 链。

在您的第二个“then”块中返回列表或将其完全删除。

【讨论】:

  • 是的问题与“.then(list => console.log(list))”有关。我删除了这个并且它起作用了。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 2020-10-30
  • 2019-10-09
  • 1970-01-01
相关资源
最近更新 更多