使用 HOC(高阶组件)和 React-Redux 连接



我试图更习惯使用高阶组件,所以我正在努力重构应用程序。我有四个不同的组件,它们都重用相同的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

最新更新