简体   繁体   中英

React + Redux HOC Loader

I have an issue with repeat code that I am trying to fix with an HOC. In my React app, I have many pages that require the props from redux to fully load in. I have been remedying this the simple way by either putting a switch statement for this.props.something and rendering a loader. I gave it a shot to create an HOC but I think my logic is off. If you could help me I would appreciate it.

Here is an example Route

import React, { Component } from 'react';
import { connect } from 'react-redux';
import LoaderHOC from '../../components/hoc/Loader';
import './Show.css';

class Show extends Component {

    render() {
        return (
            <div className="d-block w-100">
                <div className="console-show-header d-flex bg-info justify-content-center">
                    {this.props.company.name}
                </div>
            </div>
        );
    }
}

function mapStateToProps(state) {
    return { company: state.setCompany };
}

export default LoaderHOC(this.props.company)(connect(mapStateToProps)(Show));

AND MY HOC

import React, {Component } from 'react';
import Spinner from '../UI/Spinner';

const LoaderHOC = (propName) => (WrappedComonent) => {
    return class LoaderHOC extends Component {
        isEmpty(prop) {
            return (
                prop === null ||
                prop === undefined ||
                (prop.hasOwnProperty('length') && prop.length === 0) ||
                (prop.constructor === Object && Object.keys(prop).length === 0)
            );
        }

        render() {
            return this.isEmpty(this.props[propName]) ? <Spinner /> : <WrappedComonent {...this.props} />;
        }   
    }
}

export default LoaderHOC;

Try this

const LoaderHOC = (propName) => (WrappedComonent) => {
    return class LoaderHOC extends Component {
        const prop = this.props[propName];
        isEmpty(prop) {
            return (
                prop === null ||
                prop === undefined ||
                (prop.hasOwnProperty('length') && prop.length === 0) ||
                (prop.constructor === Object && Object.keys(prop).length === 0)
            );
        }

        render() {
            return this.isEmpty(this.props[propName]) ? <Spinner /> : <WrappedComonent {...this.props} />;
        }   
    }
}

export default connect(mapStateToProps)(LoaderHOC('company')(Show));

Explanation:

In order for redux to pass you updated props, you need to connect your HOC. And since you need to access the prop's value at runtime, you need to access it via this.props[propName] inside the component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM