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>
    }
}
复制代码
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值