我正在尝试更熟练地使用高阶组件,因此我正在努力重构应用程序。我有四个不同的组件,它们都重用相同的 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)
)
我在控制台中收到三个错误:
警告:Component(...):必须返回有效的 React 元素(或 null)。您可能返回了未定义、数组或其他一些无效对象。
invariant.js:42 Uncaught Error: Component(...): 必须返回有效的 React 元素(或 null)。您可能返回了未定义、数组或其他一些无效对象。
ReactDOMComponentTree.js:111 Uncaught TypeError: 无法读取 null 的属性 '__reactInternalInstance$24sdkzrlvvz'
我尝试过的其他一些技术在这个 SO post 中还有这个gist .我试过使用 compose
和不使用它,没关系。我真的很茫然。知道为什么这个 HOC 没有正确呈现吗?
此外,如果合适的话,我不反对使用 render props
作为解决方案。我需要对这两种方法进行更多练习。
最佳答案
我能够按照 Oblosys 的建议通过删除 props =>
参数来解决这个问题。我还将 AllData 中的 export
语句重新配置为:
导出默认连接(mapStateToProps,mapDispatchToProps)(WithDataRendering(AllData))
因为我真的不需要在那里使用 compose
。
关于javascript - 使用 HOC(高阶组件)和 React-Redux 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49661030/