gpt4 book ai didi

javascript - 在 "store"的上下文或 props 中找不到 "Connect(App)"

转载 作者:行者123 更新时间:2023-12-03 12:57:57 25 4
gpt4 key购买 nike

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

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

Unhandled JS Exception: Could not find "store" in either the context or props of "Connect(App)". Either wrap the root component in a , or explicitly pass "store" as a prop to "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);

最佳答案

  • 提供商,passes the store到嵌套在其中的组件,通常只需要应用于 root 组件(在您的情况下 <RootContainer>

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

建议的解决方案:

移动connect <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>
);
}
}

关于javascript - 在 "store"的上下文或 props 中找不到 "Connect(App)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41892553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com