import React, { Component } from 'react';
import http from 'utils/http';
class normalGetData extends Component{
componentDidMount() {
this.getData();
}
getData = async () => {
try {
const data = await http(xxx);
this.setState({
data
});
} catch (error) {
this.setState({
error
});
}
};
render(){
const { data } = this.state;
return <div> { data }</div>
}
}
复制代码
通常状况固然是在 componentDidMount 的时候去获取数据啦,而后放在 state 中,而后再 render 渲染数据。javascript
这里的包裹用到了Props Proxy(属性代理模式 PP)java
新建一个 withPreload.js 文件react
import React, { Component } from 'react';
import http from 'utils/http';
export default function createWithPreload(config) {
//由于咱们须要传一个url 参数,因此暴露一个 func
return function withPreload(WrappedComponent) {
return class extends Component {
// 仍是和之前的写法同样 在 ComponentDidMount 的时候取数据
componentDidMount() {
this.getData();
}
getData = async () => {
try {
// config 做为惟一的传参
const data = await http(config);
this.setState({
data
});
} catch (error) {
this.setState({
error
});
}
};
render() {
const { error, data } = this.state;
if (error) {
return '数据错啦: ' + ${error}
}
// 返回的到的数据 loadDtat={data}
// 由于用到了 WrappedComponent 包裹起来,因此须要使用 {...this.props} 去传递 props 的值给子组件
return <WrappedComponent {...this.props} loadData={data} />; } }; }; } 复制代码
上面涉及到了高阶组件的使用,有兴趣的同窗能够研究一下 react 高阶组件,其实 react 的高阶组件就是包装了另一个组件的 react 组件app
import React, { Component } from 'react';
import withPreload from './withPreload';
// 虽然咱们费了不少功夫完成了装饰器,可是如今咱们只须要这样一句话就能够预加载咱们须要的数据了,在不少页面均可以复用
@withPreload({
url: getData('/xxx/xxx/test')
})
class index extends Component{
render(){
return <div>{this.props.loadData.data}</div>
}
}
复制代码