Class Components 中获取数据
多个组件中,在哪里获取数据是最合适
一定要去官方认真阅读、理解下react哲学。
一定要去官方认真阅读、理解下react哲学
componentDidMount()
通常都是在 componentDidMount() 声明周期中获取数据
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
}
}
componentDidMount() {
fetch('http://api.mock.com/api/getUser')
.then((res) => res.json())
.then(data => this.setState({data}))
}
}
export default App;
Loading & error
请求前给个加载状态,框架的话会有统一封装。error 也是
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: false
}
}
componentDidMount() {
this.setState({isLoading: true});
fetch('http://api.mock.com/api/getUser')
.then(res => res.json())
.then(data => this.setState({
data: data.list,
isLoading: false,
error: null,
}))
.catch(error => this.setState({
error,
isLoading: false
}))
}
render() {
const {data,isLoading,error} = this.state;
if(isLoading) {
return <span>Loading...</span>
}
if(error) {
return <span>{error}</span>
}
return(
<ul>
{data.map(item => <li>{item}</li>)}
</ul>
)
}
}
export default App;