尽管使用了 componentDidMount,this.setState 并未更新初始化状态 属性 这是一个数组

this.setState is not updating an initialised state property which is an array, despite using componentDidMount

我调查了其他问题,例如:

this.setState is not updating the state property

this.setState not updating state

我很欣赏 setState 是异步的。

这是我的代码:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

class AssignmentTracker extends React.Component {
  constructor() {
      super()
      this.state= {
         assignmentsJSON : [ ],
         headerImg: "https://poster.keepcalmandposters.com/8738135.jpg"
      }
  }

  componentDidMount() {
    fetch('https://beehiveapi.lionhearttrust.org.uk/v3.5/planner/test/assignments?pageIndex=0&pageSize=20')
    .then(response => response.json())
    .then(response => {

          const {assignments} = response.items
          this.setState({
            assignmentsJSON: assignments,
          }, () => {
              console.log(this.state.assignmentsJSON);
            }) 
        })
  }

  render() {
      if (this.state.assignmentsJSON) {
        var assignmentListItems = this.state.assignmentsJSON.map((data)=> <li key={data.id}>{data.title}</li>);
        console.log(this.state.assignmentsJSON)
      }
      return (
          <div className="row">
              <header>
                  <img className="center-block img-responsive w-25" src={this.state.headerImg} alt="Keep Calm and Do Your Assignment" />
                  <h1 className="text-center">Homework Assignment Tracker</h1>
              </header>

              <div className="col-md-6 assignment-items">
                <ul>
                  {assignmentListItems}
                </ul>
              </div>

              <div className="col-md-6">
                <h1> TESTIN'PLACEHOLDER </h1>
              </div>
          </div>
      )
  }
}

ReactDOM.render(
  <AssignmentTracker/>,
  document.getElementById('root')
);




/* Developer Notes Taken Whilst this app was being made 

1- Use of CSS Input Checked in order to show assignments when clicked
2- Need to determine if radio buttons or check boxes are best for 1 
3- Dev thinks a good sense of humour is good for teamwork and even better in a education environment
4- Due to 3, an image has been selected appropiately
5- Initialise state to have data called assignmentsJSON, an array that can take in JSON data via fetch GET request done in React lifecycle method
componentDidMount() 
6- Re-factor img src of image selected in 3 to make use of initialising state, data called headerImg
7- Radio buttons for 2 would be better - if it were to look like an email UI then one at a time only
8 - Given URL endpoints not working unfortunately, have emaled Graham
9 - Using a meme api instead in the mean time
10- Use .map to loop through and display assignmentJSON prop in state after the array has been filled due to fetch in lifecycle hook
11- Hence, display each list item by 10's .map loop
*/

请注意我使用了基本的 npx create-react-app 所以 html 是带有 div 和 id app 等的基本样板。如果需要我也可以展示,但什么都没有从样板更改。

问题:

在 componentDidMount 中发出获取请求后,初始状态道具分配JSON 应该从获取中给定的端点获取所有 JSON 数据。

但是,所有 console.logs 都只是声明 this.state.assignmentsJSON 只是 [ ] 或未定义。

即使我等了很长时间,初始状态也永远不会更新。

我还尝试了不同的 URL 端点来获取数据,例如https://api.imgflip.com/get_memes 但同样的问题仍然存在

另一个初始状态 headerImg 完全可以正常工作。

任何见解将不胜感激,我是一名耐心的开发人员,所以请给予指导,我会注意的。

我具体按照上面的方法试过了,

this.setState({
            assignmentsJSON: assignments,
          }, () => {
              console.log(this.state.assignmentsJSON);
            })

但不幸的是,控制台日志只是未定义。

这会导致在使用 .map 时进一步出现问题,并且 .map 无法在未定义的情况下工作等。

非常感谢任何能提供帮助的人。

您的问题在这里:

const {assignments} = response.items

改为:const {items] = response;

您正试图从一个不存在的对象中解构一个属性。那些小花括号的意思是“嘿,给我 response.items 内部的作业”。您的回复没有名为 assignments 的属性。只有项目和分页。 JSONreturns以下object: {items: Array[20], paging: Object}.

您可以像这样登录到控制台并检查您的对象。

const { items } = response;
console.log(response);

当您尝试查看响应中的分页对象时,这会派上用场。