【问题标题】:Fetch data using React HOC(Higher Order Component), Redux and pass props使用 React HOC(高阶组件)、Redux 获取数据并传递 props
【发布时间】:2019-01-18 23:25:24
【问题描述】:

我想创建一个 HOC,它允许我调用从后端获取数据并在加载时显示加载器掩码的方法。诀窍是我希望能够为不同的组件传递不同的操作。

所以我想这样称呼它:

export default withPage({
  getLoadingStatus: getStatus,
  actionOnLoad: booksActions.getAllBooksRequest
})(ShareABookContainer);

当我在那里传递一些道具时,我定义了我的 withPage.js,如下所示:

const withPage = ({
  actionOnLoad,
  getLoadingStatus
}) => WrappedComponent => () => {
  return (
    <PageContainer
      getLoadingStatus={getLoadingStatus}
      wrappedComponent={WrappedComponent}
      actionOnLoad={actionOnLoad}
    />
  );
};

export default withPage;

PageContainer.js 是最常见的容器,所以:

const PageContainer = props => <PageComponent {...props} />;


const mapStateToProps = (state, ownProps) => ({
  ...
});

const mapDispatchToProps = (dispatch, ownProps) => {
...
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageContainer);

PageComponent 也是一个普通的 Component:

class PageComponent extends Component {
  componentDidMount() {
   ...
  }

  render() { return <this.props.wrappedComponent />;
  }
}

export default PageComponent;

发生的情况是没有渲染任何内容,如果我收到 console.log WrappedComponent:

WrappedComponent ƒ a(e,t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a);var r=function(e,t){if(!e)throw new ReferenceError("this has not been 初始化 - super()…

当我传递一些 div 时,例如测试而不是一切正常,但我需要的是渲染传递的组件。

我不知道我做错了什么,互联网上的例子也没有帮助。我无法找到像我这样的情况的示例(因此将道具传递给 HOC 并在那里使用 Redux,要么是一个,要么是另一个)。对于任何想法/建议/答案,我将不胜感激。

【问题讨论】:

  • 我不确定,但我认为您的 hoc 定义应该更像这样: const withPage = ({ actionOnLoad, getLoadingStatus }) => WrappedComponent => 所以没有最后一个空箭头函数。
  • @MaciejWojsław 感谢您的建议,但它不起作用。如果没有最后一个空箭头函数,我会得到 Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

标签: javascript reactjs redux react-redux


【解决方案1】:

尝试更简单:

return (
  <PageContainer
    getLoadingStatus={getLoadingStatus}
    actionOnLoad={actionOnLoad} >
    <WrappedComponent />
  </PageContainer>
);

顺便说一句,反应相当“不喜欢”&lt;this.props.wrappedComponent /&gt; 没有错误??

当需要动态组件时,我可能会使用类似的东西:

const Wrapped = this.props.wrappedComponent;
render () { return <Wrapped /> }

变量名称必须大写。

【讨论】:

  • 为什么变量名必须大写?它不应该导致这样的错误。
  • 理论上不行,但这对我有用。这是一个多步骤转换,恕我直言 BABEL 不识别/解释分配值的类型,它具有简单的逻辑'JSX 组件名称必须大写才能被视为 ' - '小写 = 普通 html 标记'。它不关心它是否会工作,它只是以第一种或第二种方式处理“标签”。
  • 谷歌搜索'jsx dynamic component name' - 你会发现这个,大写选项和&lt;$component /&gt; 作为解决方案。
猜你喜欢
  • 1970-01-01
  • 2018-09-14
  • 2019-05-18
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
  • 2017-04-28
  • 2016-10-13
相关资源
最近更新 更多