首页 文章

如何明确地将商店作为道具传递给“Connect()”

提问于
浏览
17

我试图测试我的React组件并得到以下错误 .

不变违规:无法在“Connect()”的上下文或道具中找到“store” . 将根组件包装在<Provider>中,或者显式地将“store”作为prop传递给“Connect()” .

在测试中渲染Component时出错 .

beforeEach(() => {
  Component = TestUtils.renderIntoDocument(<SideMenu />);
});

在页面上呈现Component时,它工作正常 . 但是在测试中,我无法将存储明确地传递给Component .

有人能指出正确的方向吗?

3 回答

  • 3

    connectreact-redux 提供的装饰器 . 对redux的组件 connect 是一个智能组件,并期望存储可以通过 prop 或通过 Provider 显示错误消息 .

    在测试智能组件时,您可以提供模拟商店作为 prop . 但是,当行中有另一个子组件,谁希望 store 时, prop 方式将不起作用 .

    这是一种将 store 提供给 import 是订阅 store 的子组件的组件的方法 .

    const initialState = {key: 'value'};
    const store = createStore(initialState);
    
    component = TestUtils.renderIntoDocument(
      <Provider store={store(initialState)}>
        {() => <SideMenu />}
      </Provider>
    );
    
  • 5

    要回答这个问题(我遇到了这个并且接受的答案不是我需要的),请创建一个新方法,如:

    function connectWithStore(store, WrappedComponent, ...args) {
      let ConnectedWrappedComponent = connect(...args)(WrappedComponent)
      return function (props) {
        return <ConnectedWrappedComponent {...props} store={store} />
      }
    }
    

    然后,为了连接,使用:

    const ConnectedApp = connectWithStore(store, App, mapStateToProps, mapDispatchToProps,)
    
    export default ConnectedApp;
    

    看这里:https://github.com/reactjs/react-redux/issues/390#issuecomment-221389608

  • 2

    在大多数情况下,我发现在测试中导入组件本身对我来说很好 .

    SideMenu.js:

    export class SideMenu extends React.Component {
     // implementation
    }
    
    export default connect(mapStateToProps,)(SideMenu)
    

    SideMenu.spec.js:

    import { SideMenu } from 'path/to/SideMenu.js'
    
    const props = {
      // provide all necessary stubs and mocks for redux props and actions 
    }
    component = TestUtils.renderIntoDocument(<SideMenu {...props} />);
    

    注意:正如Салман所指出的那样,当有另一个子组件下线时,这种方法将不起作用,谁期望 store .

相关问题