簡體   English   中英

在React-Redux Connect中使用HOC(高階組件)

[英]Using a HOC (higher order component) with React-Redux connect

我正在嘗試使用更高階的組件,因此我正在重構應用程序。 我有四個不同的組件,它們都重復使用相同的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帖子要點中 我試過使用compose而不使用它,沒關系。 我真的很茫然。 有什么想法為什么此HOC無法正確呈現?

另外,如果合適的話,我也不反對使用render props作為解決方案。 我需要對這兩種方法進行更多練習。

如Oblosys所建議,我可以通過刪除props =>參數來解決此問題。 我還將AllData中的export語句重新配置為:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM