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 渲染数据。javascript

使用装饰器的方法,包裹一下咱们经常使用的预加载数据,须要渲染的地方。

  • 这里的包裹用到了Props Proxy(属性代理模式 PP)java

    • 不明白的同窗能够看看 [react 高阶组件 代理模式]
  • 新建一个 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>
    }
}
复制代码
相关文章
相关标签/搜索