componentDidUpdate() 主要工作,但不呈现新数据

componentDidUpdate() working mostly, but not rendering new data

我正在使用 componentDidUpdate() 方法,在大多数情况下,它正在做它应该做的事情。它运行函数以从 API 获取数据并将其记录到控制台。问题是它不会在前端呈现新数据。它呈现新数据的唯一时间是组件是否实际安装(如果页面已刷新)。我觉得我很接近,但已经走到了死胡同。这是我的代码:

import React from 'react';
import Nav from './Nav';

class List extends React.Component {
constructor(props) {
super(props);
this.state = {
  APIData: []
}
}

getAPIData() {
const url = `http://localhost:3001${this.props.location.pathname}`;
return fetch(url, {
  method: 'GET',
  mode: 'CORS',
  headers: {
    'Accept': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
    return data;
  }).catch(err => { console.log('Error: ', err) });
};

dataList() {
return (
  <div>
  {this.state.APIData.map((APIData) => (
    <p> And the data returned is -> {APIData.firstName} 
{APIData.lastName} !</p>
  )
  )}
  </div>
) 
}

componentDidMount() {
console.log(this.props.location.pathname);

this.getAPIData()
  .then(data => {
    console.log('in List.js ', data);
    this.setState({
      APIData: data
    });
  });
}

componentDidUpdate(prevProps, prevState) {
console.log(this.props.location.pathname);
// only update if the data has changed
this.getAPIData()
.then(data => {
  if (prevProps.data !== this.props.data) {
    this.setState({
      APIData: data
    });
  }
  console.log(data);
});
}

render() {
return (
  <div>
    <Nav />
    <br />
    <br />
    <br />
    <br />
    <div>
      {/* {this.state.APIData.map((APIData) => (
        <p> And the data returned is -> {APIData.firstName} 
 {APIData.lastName} !</p>
      )
      )} */}
      {this.dataList()}

    </div>

  </div>
 );
 }
 }



 export default List;

我想可能是这个街区:

if (prevProps.data !== this.props.data) {
  this.setState({
    APIData: data
  });
}

你真的向这个组件传递了一个 data 道具吗?

如果不是,那么它将检查是否 undefined !== undefined 并且永远不会执行。

如果是,那么您可能会检查数据引用是否确实发生了变化,或者您只是在改变对象的内部。