1

I am using the componentDidUpdate() method and for the most part, it is doing what it should. It runs the function to get the data from the API as well as logs it to the console. The problem is that it does not render the new data on the front end. The only time it renders the new data is if the component actually mounts (if the page is refreshed). I feel like I'm very close, but have hit a dead end. Here is my code:

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;
4

1 回答 1

0

我认为可能是这个块:

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

你实际上是在data向这个组件传递一个道具吗?

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

如果你是,那么你可能会检查数据引用是否真的在改变,或者你只是在改变对象的内部。

于 2018-06-05T01:07:47.323 回答