小编典典

在“ Connect(App)”的上下文或道具中找不到“商店”

reactjs

将多个文件的内容合并到一个文件中以作为Redux的配置后,Redux的配置出现问题。

如何解决store,同时将其保存在一个文件中?

未处理的JS异常:在“ Connect(App)”的上下文或道具中找不到“商店”。可以将根组件包装在中,也可以将“存储”作为道具明确传递给“
Connect(App)”。

'use strict';
import React, { Component } from 'react';
import { createStore, applyMiddleware, combineReducers, bindActionCreators } from 'redux';
import { Provider, connect } from 'react-redux';
import thunk from 'redux-thunk';
import * as screenActions from './redux/actions/screenActions';

import * as reducers from './redux/stores/reducers';

const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const reducer = combineReducers(reducers);
const store = createStoreWithMiddleware(reducer);

import RootContainer from './redux/views/containers/rootContainer';

class App extends Component {
  render() {
    const { state, actions } = this.props;
    return (
      <Provider store={store}>
        <RootContainer />
      </Provider>
    );
  }
}

export default connect(
  (state) => ({
    state: state.reducer
  }),
  (dispatch) => ({
    actions: bindActionCreators(screenActions, dispatch)
  })
)(App);

阅读 319

收藏
2020-07-22

共1个答案

小编典典

  • 提供程序, 将商店传递 给嵌套在其中的组件,通常只需要将其应用于 组件(在您的情况下)<RootContainer>

  • connect与提供存储的组件连接, 而不 与提供存储的组件连接。

建议的解决方案:

MOVEconnect
<RootContainer>组件文件代替,并通过connect了RootContainer并 没有 在App组件:

export default connect(
  (state) => ({
    state: state.reducer
  }),
  (dispatch) => ({
    actions: bindActionCreators(screenActions, dispatch)
  })
)(RootContainer);  // <<--- here :)

更新:

鉴于OP希望在同一个文件中实现所有这些目标,因此您必须创建一个React元素,该元素代表通过connect创建的Redux容器,因此:

'use strict';
import React, { Component } from 'react';
import { createStore, applyMiddleware, combineReducers, bindActionCreators } from 'redux';
import { Provider, connect } from 'react-redux';
import thunk from 'redux-thunk';
import * as screenActions from './redux/actions/screenActions';

import * as reducers from './redux/stores/reducers';

const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const reducer = combineReducers(reducers);
const store = createStoreWithMiddleware(reducer);

import RootContainer from './redux/views/containers/rootContainer';

// name has to be capitalised for React to recognise it as an element in JSX
const ConnectedRoot = connect(
  (state) => ({
    state: state.reducer
  }),
  (dispatch) => ({
    actions: bindActionCreators(screenActions, dispatch)
  })
)(RootContainer);

class App extends Component {
  render() {
    const { state, actions } = this.props;
    return (
      <Provider store={store}>
        <ConnectedRoot />    <------USE IT HERE
      </Provider>
    );
  }
}
2020-07-22