useDispatch() 错误:找不到 react-redux 上下文值;请确保组件被包裹在 <Provider> 中. [英] useDispatch() Error: Could not find react-redux context value; please ensure the component is wrapped in a <Provider>
问题描述
我正在尝试使用 React-Redux 库,但在标题上出现错误.我用 Provider 包装了我的组件,但我仍然收到错误,只有当我实现了 useDispatch() 钩子.
I am trygin to use React-Redux library and I am getting the error on the title. I wrapped my components with Provider but I still get the error, only if I implement the useDispatch() hook.
应用程序运行良好,直到我添加了 useDispatch() 行.可以删除有关调度函数的其余行,但我仍然遇到相同的错误.
The app worked fine, until I added the useDispatch() line. The rest of lines regarding the dispatch function can be removed and I still get the same error.
如果您能帮助我,我将不胜感激.谢谢
If you could help me I would really appreciate it. Thanks
这是我的代码:
import 'react-native-gesture-handler';
import {NavigationContainer} from '@react-navigation/native';
import Navigator from './navigation/Navigator';
import React, {useEffect, useState, useCallback} from 'react';
import {SafeAreaView, StyleSheet, Text, View} from 'react-native';
import {createStore, combineReducers} from 'redux';
import {Provider, useDispatch} from 'react-redux';
import dataReducer from './store/reducers/dataReducer';
import {CONSTANTS} from './constants/constants';
import {saveInitialData} from './store/actions/dataActions';
const App = () => {
const [fetched, setFetched] = useState(initialState);
const dispatch = useDispatch();
const saveInitialDataHandler = useCallback(data => {
dispatch(saveInitialData(data));
callback;
}, []);
const rootReducer = combineReducers({
content: dataReducer,
});
const store = createStore(rootReducer);
useEffect(() => {
fetchData();
}, []);
const fetchData = () => {
fetch(CONSTANTS.database)
.then(response => response.json())
.then(responseJSON => {
setFetched(true);
saveInitialDataHandler(responseJSON);
});
};
if (!fetched) {
return (
<Provider store={store}>
<View stlye={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text></Text>
</View>
</Provider>
);
} else {
return (
<Provider store={store}>
<NavigationContainer>
<SafeAreaView style={styles.SafeAreaView}>
<Navigator></Navigator>
</SafeAreaView>
</NavigationContainer>
</Provider>
);
}
};
const styles = StyleSheet.create({
SafeAreaView: {flex: 1},
});
export default App;
推荐答案
App
必须包含在 provider 中,因为您在其中使用了 useDispatch
.现在只是个孩子.Provider
设置上下文,以便只有它的孩子可以访问它,而不是父母.
App
must be wrapped in provider since you are using useDispatch
in it. Right now it's just a child. Provider
sets the context so only its children can have access to it, not a parent.
一种解决方案是为其创建一个包装器组件:
One solution would be to create a wrapper component for it:
const AppWrapper = () => {
const store = createStore(rootReducer);
return (
<Provider store={store}> // Set context
<App /> // Now App has access to context
</Provider>
)
}
const App = () => {
const dispatch = useDispatch(); // Works!
...
这篇关于useDispatch() 错误:找不到 react-redux 上下文值;请确保组件被包裹在 <Provider> 中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!