wil*_*gon 4 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
Run Code Online (Sandbox Code Playgroud)
这是我试图用 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)
)
Run Code Online (Sandbox Code Playgroud)
我在控制台中收到三个错误:
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 post和这个gist 中。我试过使用compose和不使用它,没关系。我真的很茫然。任何想法为什么这个 HOC 不能正确渲染?
另外,render props如果更合适,我不反对将其用作解决方案。我需要对这两种方法进行更多练习。
我能够通过删除props =>Oblosys 建议的论点来解决这个问题。我还将exportAllData 中的语句重新配置为:
export default connect(mapStateToProps, mapDispatchToProps)(WithDataRendering(AllData))
因为我真的不需要在compose那里使用。
| 归档时间: |
|
| 查看次数: |
5098 次 |
| 最近记录: |