React Js组件DidMount Ajax调用setstate不更新状态


import React, { Component} from 'react';
import { Route } from 'react-router';
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.state = {
league: {
teams: {
data: [],
loaded: false,
config: {
icon: true,
parentId: 'leftSideTreeView'
}
},
players: {
data: [],
loaded: false,
config: {
icon: true,
parentId: 'leftSideTreeView'
}
},
games: {
data: [],
loaded: false,
config: {
icon: true,
parentId: 'leftSideTreeView'
}
},
error: false
}
};
}
componentDidMount() {
this.getTeamsHandler();
}
getTeamsHandler = () => {
axios.get('/api/League/GetTeams')
.then((response) => {
let prevState = [...this.state.league.teams];
prevState.data = response.data;
prevState.loaded = true;
this.setState({ teams: prevState });
})
.catch((error) => {
this.setState({ error: error });
});
}
renderTeamsHandler = () => {
let games = this.state.league.games;
let content = null;
if (games.data.length > 0) {
content = games.data.map((team, index) => {
return <div key={index}>{team.teamName}</div>;
});
}
return content;
}
render() {
let Team = this.renderTeamsHandler();
return (
<div>
{Team}
</div>
);
}
}
export default App;

Ajax调用确实将数据设置为prevState.Data,但在渲染数据时,状态与Ajax调用之前相同。这让我很困惑,因为这一切在我看来都是正确的。这可能是异步问题吗?如果是这样的话,为什么我以前做过这样的事情,却没有任何问题。

感谢您提前提供的帮助。

我怀疑有两部分问题。

首先,getTeamsHandler中的setState:

axios.get('/api/League/GetTeams')
.then((response) => {
let prevTeam = [...this.state.league.teams];
prevTeam.data = response.data;
prevTeam.loaded = true;
this.setState(prevState => ({
league: {
...prevState.league,
teams: prevTeam
}
})
})
.catch((error) => {
this.setState(prevState => ({
league: {
...prevState.league,
error: error
}
});
});

其次,我想renderTeamsHandler中有一些错误。获取日期并在团队中设置,但在renderTeams Handler中使用group。状态中的group是。

renderTeamsHandler = () => {
let teams = this.state.league.teams;
let content = null;
if (teams.data.length > 0) {
content = teams.data.map((team, index) => {
return <div key={index}>{team.teamName}</div>;
});
}
return content;
}

相关内容

  • 没有找到相关文章

最新更新