说明
- react 初学者
- 怎么使用装饰器?
理解一下 react 中装饰器的使用
- 看看这篇文章 react 装饰器的使用
需求分析
- 每次我们在加载页面的时候需要加载一些数据
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 渲染数据。
使用装饰器的方法,包裹一下我们常用的预加载数据,需要渲染的地方。
-
这里的包裹用到了Props Proxy(属性代理模式 PP)
- 不明白的同学可以看看 [react 高阶组件 代理模式]
-
新建一个 withPreload.js 文件
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 组件
- 然后我们就可以这样来使用封装好的装饰器了
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>
}
}
复制代码