所以我正在使用 github api,我想使用子组件中状态的数据,但它将一次采用初始状态,并在异步函数完成后使用我设置的数据。 如何仅使用 setState 中的数据?
fetch('https://api.github.com/search/topics?q=javascript', {
headers: {
'Accept': 'application/vnd.github.mercy-preview+json'
}
})
.then(res => res.json())
.then(json => this.setState({ data: json }));
}
render() {
console.log(this.state);
return (
<Router>
<Header jsTrendingName={this.state.data}/>
<Switch>
<Route path="/" exact component={Dashboard} />
<Route path="/home" component={Home} />
</Switch>
</Router>
)
最佳答案
如果还没有,您需要在组件的 componentDidMount
生命周期中进行 API 调用。
Additionally you should maintain the state of your API call (
isFetching
flag in your initial state).
...
getJSData = () => {
// set isFetching to true before API call is made
this.setState({ isFetching: true });
fetch('https://api.github.com/search/topics?q=javascript', {
headers: {
'Accept': 'application/vnd.github.mercy-preview+json'
}
})
.then(res => res.json())
.then(json => this.setState({ data: json }));
}
componentDidMount() {
// Call your API
this.getJSData();
}
...
您的初始状态是:
state = {
isFetching: false,
data: null
}
然后在render
方法中,检查API调用状态:
render() {
const { isFetching } = this.state;
if (isFetching) {
return <span> Loading ... </span>
}
// isFetching is false now since API call is complete.
console.log(this.state);
return (
<Router>
<Header jsTrendingName={this.state.data}/>
<Switch>
<Route path="/" exact component={Dashboard} />
<Route path="/home" component={Home} />
</Switch>
</Router>
)
}
关于javascript - 我怎样才能只使用新设置的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58624767/