所以我正在使用github api,我想在子组件中使用state中的数据,但是它将一次处于初始状态,并且在完成异步功能后设置了我设置的数据。如何仅使用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>
)
this.state = { data: []};
componentDidMount(){
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.items}));
}
render() {
const {data} = this.state;
return (
<Router>
<Header jsTrendingName={data}/>
<Switch>
<Route path="/" exact component={Dashboard} />
<Route path="/home" component={Home} />
</Switch>
</Router>
)
}
如果尚未,则需要在组件的componentDidMount
生命周期中进行API调用。
另外,您应该保持API调用的状态(
isFetching
标志处于初始状态)。
...
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>
)
}
您应在调用api并通过检查this.state.data不为空而保存到状态时等待数据。
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.data && this.state.data); // You should wait for data here then log it or use it.
return (
<Router>
<Header jsTrendingName={this.state.data}/>
<Switch>
<Route path="/" exact component={Dashboard} />
<Route path="/home" component={Home} />
</Switch>
</Router>
)