为了账号安全,请及时绑定邮箱和手机立即绑定

创建一个可重用的Redux包装器

创建一个可重用的Redux包装器

ABOUTYOU 2021-05-05 18:24:06
我正在使用Webpacker和react-rails的RoR项目中工作。我们正在逐渐从haml转向React。因此,我们正在做的每个页面我们react_component('page_to_render')也在使用Redux,我一直在Provider中直接调用我的组件,并且运行良好。由于我们使用这种方式的原因,从某种意义上讲,每个页面都是它自己的React应用程序,我正在尝试制作一个可重用的组件来传递商店。我的想法是:import React, { Component } from 'react'import { Provider } from 'react-redux'import store from './store'class ReduxState extends Component {  render() {    return (      <Provider store={store}>        {this.props.children}      </Provider>    )  }}export default ReduxState因此,对于每个页面,我们只需要将其包装在中<ReduxState></ReduxState>,但是当我这样做时,我得到:Could not find "store" in the context of "Connect(BillingPage)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(BillingPage) in connect options.似乎应该将存储传递给任何包装的东西,但事实并非如此。我觉得我可能缺少有关Redux工作原理的信息。有没有更好的方法来解决这个问题?
查看完整描述

1 回答

?
慕斯王

TA贡献1864条经验 获得超2个赞

在深入了解我的错误之后,我意识到我正在JSX中返回Provider,并且BillingPage类本身没有引用ReduxState


我意识到我需要一个HOC。解决方案如下:


import React, { Component } from 'react'

import { Provider } from 'react-redux'


import store from './store'


const ReduxState = WrappedComponent => {

  return class extends Component {

    render() {

      return (

        <Provider store={store}>

          <WrappedComponent {...this.props} />

        </Provider>

      )

    }

  }

}


export default ReduxState

const composedHoc = compose(

  ReduxState,

  connect(

    mapStateToProps,

    {

      addBill,

      removeBill

    }

  )

)


export default composedHoc(BillingPage)


查看完整回答
反对 回复 2021-05-27
  • 1 回答
  • 0 关注
  • 159 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信