【发布时间】:2018-11-14 08:46:38
【问题描述】:
我正在使用 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;
【问题讨论】:
-
大多数 API 都有针对这些情况的更新功能。由于我不使用您的框架,因此我无法提供更多帮助。
标签: javascript reactjs lifecycle-hook