猿问

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

我正在使用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工作原理的信息。有没有更好的方法来解决这个问题?


ABOUTYOU
浏览 161回答 1
1回答

慕斯王

在深入了解我的错误之后,我意识到我正在JSX中返回Provider,并且BillingPage类本身没有引用ReduxState我意识到我需要一个HOC。解决方案如下:import React, { Component } from 'react'import { Provider } from 'react-redux'import store from './store'const ReduxState = WrappedComponent => {&nbsp; return class extends Component {&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <Provider store={store}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <WrappedComponent {...this.props} />&nbsp; &nbsp; &nbsp; &nbsp; </Provider>&nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }&nbsp; }}export default ReduxStateconst composedHoc = compose(&nbsp; ReduxState,&nbsp; connect(&nbsp; &nbsp; mapStateToProps,&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; addBill,&nbsp; &nbsp; &nbsp; removeBill&nbsp; &nbsp; }&nbsp; ))export default composedHoc(BillingPage)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答