我正在我的 React 应用程序中发出返回团队数据的 GET
请求。我在父组件中进行此操作,然后将其传递给子 Loop
组件。 GET
请求正在工作,但当它到达 render
函数时,它是未定义的,可能是因为我的 GET
请求尚未完成。我尝试过使用 componentWillMount
但遇到了同样的问题。
有人能看出我做错的事情吗?我对 React 还很陌生。
请参阅下面我的代码。
var App = React.createClass({
getInitialState: function() {
return {
teams: []
}
},
componentDidMount: function() {
$.get(url, function(data) {
this.state.teams.push(data)
});
},
render: function() {
console.log(this.state.teams)
return (
< div >
< Loop teams={this.state.teams} / >
< /div>
)
}
});
var Loop = React.createClass({
render: function() {
var teamList = this.props.teams.map(function(team, index){
return(
<h1 key={index}>
{team.name}
</h1 >
)
}) return <ul > {teamList} < /ul>
}
})
最佳答案
您的方向是正确的:您收到 undefined
的原因是请求尚未完成。
那是因为您的代码使用 this.state
直接更改状态。但您的请求是异步的,因此您需要使用 setState
,它仅在请求完成时更新状态:
componentDidMount: function() {
$.get(url, function(data) {
this.setState({
teams: data,
})
}.bind(this));
}
参见the docs .
关于javascript - 在 React 中使用 GET 请求中的数据并在子组件中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40673868/