使用带有React-Redux连接的HOC(高阶组件)

时间:2018-04-04 21:53:59

标签: javascript reactjs redux react-redux higher-order-components

我试图使用更高阶的组件更加舒服,因此我正在努力重构应用程序。我有四个不同的组件,它们都重用相同的fetchData请求,以及错误/加载条件。我的计划是将这些可重用的数据放入HOC中。我已尝试过StackOverflow,Reddit,Github等许多不同的例子,但在我的特定情况下,它们都没有。

这是我的HOC:

const WithDataRendering = WrappedComponent => props => {
class WithDataRenderingComponent extends Component {
    componentDidMount() {
    this.props.fetchData(url)
    }
    render() {
    if (this.props.hasErrored) {
        return (
        <p>
            Sorry! There was an error loading the items:{" "}
            {this.props.hasErrored.message}
        </p>
        )
    }

    if (this.props.isLoading) {
        return (
        <div>
            <Skeleton count={10} />
        </div>
        )
    }

    return <WrappedComponent {...this.props} />
    }
}
const mapStateToProps = state => {
    return {
    data: state.data,
    hasErrored: state.dataHasErrored,
    isLoading: state.dataIsLoading
    }
}

const mapDispatchToProps = dispatch => {
    return {
    fetchData: url => dispatch(fetchData(url))
    }
}
return connect(mapStateToProps, mapDispatchToProps)(
    WithDataRenderingComponent
)
}

export default WithDataRendering

这是我试图用HOC包装的一个组件:

export class AllData extends Component<Props> {
    render() {
        return (
        ...
        )
    }
}

const mapStateToProps = state => {
    return {
        data: state.data,
        hasErrored: state.dataHasErrored,
        isLoading: state.dataIsLoading
    }
}

const mapDispatchToProps = dispatch => {
    return {
        fetchData: url => dispatch(fetchData(url))
    }
}

export default compose(
    connect(mapStateToProps, mapDispatchToProps),
    WithDataRendering(AllData)
)

我在控制台中收到三个错误:

Warning: Component(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

invariant.js:42 Uncaught Error: Component(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

ReactDOMComponentTree.js:111 Uncaught TypeError: Cannot read property '__reactInternalInstance$24sdkzrlvvz' of null

我尝试过的其他几种技巧都在SO postgist中。我尝试使用compose而不使用它,并不重要。我真的很茫然。有什么想法为什么这个HOC没有正确呈现?

另外,如果更合适,我并不反对使用render props作为解决方案。我需要用两种方法进行更多练习。

1 个答案:

答案 0 :(得分:3)

我能够通过删除Oblosys建议的props =>参数来解决这个问题。我还将AllData中的export语句重新配置为:

export default connect(mapStateToProps, mapDispatchToProps)(WithDataRendering(AllData))

因为我真的不需要在那里使用compose