gpt4 book ai didi

reactjs - useDispatch()错误: Could not find react-redux context value; please ensure the component is wrapped in a

转载 作者:行者123 更新时间:2023-12-03 14:16:13 55 4
gpt4 key购买 nike

我正在尝试使用 React-Redux 库,但在标题上出现错误。我用 Provider 包装了我的组件,但仅当我实现 useDispatch() Hook 时,我仍然收到错误。

应用程序运行良好,直到我添加了 useDispatch() 行。关于调度函数的其余行可以删除,但我仍然得到相同的错误。

如果您能帮助我,我将非常感激。谢谢

这是我的代码:

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 必须包装在提供程序中,因为您在其中使用 useDispatch 。现在还只是个 child 。 Provider 设置上下文,以便只有其子级可以访问它,而父级则不能。

一种解决方案是为其创建一个包装组件:

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!
...

关于reactjs - useDispatch()错误: Could not find react-redux context value; please ensure the component is wrapped in a <Provider>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60329421/

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