javascript – 无法在“Connect(App)”的上下文或道具中找到“store”
作者:互联网
将多个文件的内容合并为一个以作为Redux的配置后,我遇到了错误配置的Redux的问题.
如何解决存储,同时将其保存在一个文件中?
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);
解决方法:
> Provider,passes the store到嵌套在其中的组件,通常只需要应用于根组件(在你的情况下< RootContainer>
> connect connect与提供商店的组件连接,而不是与提供商店的组件连接.
建议的解决方案:
将连接移动到< RootContainer>而是组件文件,并传递连接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,reactjs,react-native,redux,react-redux 来源: https://codeday.me/bug/20190929/1830371.html