找不到“商店"在“连接"的上下文或道具中 [英] Could not find "store" in either the context or props of "Connect"
问题描述
我已经使用 React Native 几年了,直到最近才需要在一个新的、更复杂的项目中使用 Redux.我目前正在学习一些教程,试图以自己的方式完成基础知识.
I have been using React Native for a few years and have only recently needed to utilise Redux on a new, more complex project. I am currently in the process of following a number of tutorials trying to work my way through the basics.
我目前遇到以下错误:
Invariant Vilation:在Connect(App)"的 props 上下文中都找不到store"
我找到了许多关于此错误信息的帖子,但由于我目前掌握的知识很少,我不确定如何正确实施修复.
I have found a number of posts with information about this error but because of the low amount of knowledge I currently have, I am unsure as to how to correctly implement a fix.
这个项目是用 create-react-native-app
创建的,我正在使用 Expo 应用程序进行测试.
This project was created with create-react-native-app
and I am using the Expo app to test.
在我看来,这应该可行,因为 App
的根元素是一个 Provider
元素,将 store
作为道具传递,这似乎矛盾错误是什么意思.
In my eyes this should work because the root element of App
is a Provider
element passing the store
as a prop which seems to contradict what the error is saying.
configureStore.js
import { createStore, applyMiddleware } from 'redux';
import app from './reducers';
import thunk from 'redux-thunk';
export default function configureStore() {
return createStore(app, applyMiddleware(thunk));
}
App.js:
import React from 'react';
import { Text } from 'react-native';
import { Provider, connect } from 'react-redux';
import configureStore from './configureStore';
import fetchPeopleFromAPI from './actions';
const store = configureStore();
export class App extends React.Component {
componentDidMount() {
props.getPeople()
}
render() {
const { people, isFetching } = props.people;
return (
<Provider store={store}>
<Text>Hello</Text>
</Provider>
);
}
}
function mapStateToProps(state) {
return {
people: state.people
}
}
function mapDispatchToProps(dispatch) {
return {
getPeople: () => dispatch(fetchPeopleFromAPI())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
推荐答案
您正在尝试访问 App
组件中的商店,甚至在它被传递之前.因此它无法找到store
.
You are trying to access the store in the App
component even before it has been passed. Therefore it is not able to find the store
.
您需要制作一个单独的组件并使用 react-redux
将其连接起来,例如
You need to make a separate component and connect that using react-redux
such as
<Provider store={store}>
<ConnectedComponent />
</Provider>
...
class ConnectedComponent extends React.Component {
componentDidMount () {
this.props.getPeople()
}
render() {
return (
<View>
<Text> ... </Text>
</View>
)
}
}
function mapStateToProps(state) {
return {
people: state.people
}
}
function mapDispatchToProps(dispatch) {
return {
getPeople: () => dispatch(fetchPeopleFromAPI())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ConnectedComponent);
这篇关于找不到“商店"在“连接"的上下文或道具中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!