【发布时间】:2018-10-10 16:36:42
【问题描述】:
我有一个组件,我在其中根据之前单击的项目 ID 获取数据。获取成功,console.log 显示正确的数据,但数据因 this.setState 丢失。我在同一个组件中有 componentDidUpdate 和 componentDidMount,不确定这是否可以,或者这两个可能会互相混淆?
代码如下:
const teamAPI = 'http://localhost:8080/api/teams/'
const playerAPI = 'http://localhost:8080/api/playersByTeam/'
const matchAPI = 'http://localhost:8080/api/match/'
class View extends Component {
constructor() {
super();
this.state = {
data: [],
playersData: [],
update: [],
team1: [],
team2: [],
matchData: [],
testTeam: [],
};
}
componentDidUpdate(prevProps) {
if (prevProps.matchId !== this.props.matchId) {
fetch(matchAPI + this.props.matchId)
.then((matchResponse) => matchResponse.json())
.then((matchfindresponse) => {
console.log(matchfindresponse);
this.setState({
matchData:matchfindresponse,
testTeam:matchfindresponse.team1.name,
})
})
}
}
componentDidMount() {
fetch(teamAPI)
.then((Response) => Response.json())
.then((findresponse) => {
console.log(findresponse)
this.setState({
data:findresponse,
team1:findresponse[0].name,
team2:findresponse[1].name,
})
})
fetch(playerAPI + 82)
.then(playerResponse => playerResponse.json())
.then(players => {
console.log(players)
this.setState({
playersData:players
})
})
}
第一次渲染也给出了这个警告:
Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.
Please check the code for the View component.
ComponentDidMount 中的所有内容在渲染中都可以正常工作,但 componentDidUpdate 中的 {this.state.matchData} 和 {this.state.testTeam} 为空。
问题可能是 ComponentDidMount 重新渲染了导致 ComponentDidUpdate 中的数据丢失的组件,如果是这样,我该如何解决这个问题?
像这样尝试过 ComponentWillReceiveProps 但仍然没有运气
componentWillReceiveProps(newProps) {
if (newProps.matchId !== this.props.matchId) {
fetch(matchAPI + newProps.matchId)
.then((matchResponse) => matchResponse.json())
.then((matchfindresponse) => {
console.log(matchfindresponse.team1.name);
console.log(this.props.matchId + ' ' + newProps.matchId);
this.setState({
matchData:matchfindresponse.team1.name,
})
})
}
}
【问题讨论】:
-
:o 抱歉,也许我使用的 React 版本太旧了...上次我使用它时,我很确定我必须像那样合并!删除它,再次抱歉...我要深入了解一下!
-
看起来你应该使用
componentWillReceiveProps而不是componentDidUpdate
标签: javascript reactjs api react-router fetch