【问题标题】:Passing redux state to dispatcher将 redux 状态传递给调度程序
【发布时间】:2019-08-16 16:11:44
【问题描述】:

我目前正在编写一个 React 项目(使用 redux 和 recompose)并尝试将我的 redux 状态传递给我的连接内的调度。

我想避免编写我的连接代码两次,但必须这样做才能使currentLocaleCode 出现在状态中,以便调度可以从我的本地状态中获取它。

看起来是这样的:

export default compose(
  connect(
    (
      {
        locales: { currentLocaleCode }
      }
    ) => ({ currentLocaleCode })
  ),
  connect(null, (dispatch) => ({
    fetchPage: () =>
      dispatch(pagesActions.fetchPage(currentLocaleCode))
  })),
...

我想立即使用 currentLocaleCode 并实现以下目标:

export default compose(
  connect(
    ({ locales: { currentLocaleCode } }) => ({ currentLocaleCode }),
      (dispatch, { currentLocaleCode }) => ({
        fetchPage: () =>
          dispatch(pagesActions.fetchPage(currentLocaleCode))
      }),
...

这可能吗?

【问题讨论】:

    标签: reactjs redux recompose


    【解决方案1】:

    您可以简单地将数据作为道具传递给组件并使用所需数据调用动作创建者,而不是使用两个连接 HOC

    喜欢

    export default compose(
      connect(({locales: { currentLocaleCode }}) => ({ currentLocaleCode }),
      (dispatch) => ({
        fetchArticles: (dispatch) => ({
          fetchPage: =>
            (currentLocaleCode) => dispatch(pagesActions.fetchPage(currentLocaleCode))
        })
      })),
    ...
    

    在连接的组件中,您可以调用 fetchPage

    this.props.fetchPage(this.props.currentLocaleCode);
    

    【讨论】:

    • 嗨,Shubham,我不小心添加了一些不应该存在的额外代码。我现在已经删除了。基本上fetchArticlesfetchPage 不应该相互写入,我的问题是如何避免两次写入connect
    • 关于您的评论,我想避免每次调用我的方法时都必须传递currentLocaleCode,因为它已经在我的状态下可用。
    猜你喜欢
    • 2019-02-17
    • 2020-10-29
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    相关资源
    最近更新 更多