在"Connect(App)"的上下文或道具中都找不到"store"



将多个文件的内容合并为一个文件以用作 Redux 的配置后,我遇到了配置错误的 Redux 问题。

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

未处理的 JS 异常:在任一上下文中都找不到"存储" 或"连接(应用程序)"的道具。将根组件包装在 ,或显式将"存储"作为道具传递给"连接(应用程序)"。

'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);
  • 提供程序,将存储传递给嵌套在其中的组件,通常只需要应用于组件(在您的情况下<RootContainer>

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

建议的解决方案:

connect移动到<RootContainer>组件文件,并传递connect根容器而不是应用程序组件:

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>
    );
  }
}
我在

使用时遇到了这样的问题:

import connect from "react-redux/lib/connect/connect";

取而代之的是:

import {connect} from "react-redux";

在你的根索引中放置提供程序。

<Provider store={store}>
    <App />
</Provider>,

相关内容

  • 没有找到相关文章

最新更新