我正在try 使用React Redux库,但标题上出现了错误.我用Provider包装了我的组件,但只有在实现useDispatch()钩子的情况下,我仍然会出错.

在我添加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必须包装在provider中,因为您在其中使用useDispatch.现在只是个子元素.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相关问答推荐

无法使用#13;或br将新行设置为文本区域'"&"<>

REACT路由DOM根据参数呈现不同的路由

Reaction Axios多部分/表单-数据数组不工作

单击空白区域时,Reaction Multiple下拉组件不关闭

导致useState中断的中断模式

捕获表单数据时的Reactjs问题

对搜索引擎优化来说,react 头盔的异步足够了吗?

在每页上应用字体-NextJS

Reaction路由-如何在布局路由内呈现&q;/:id&q;路由

useEffect不重新渲染

如何清除过滤器搜索的状态

这个简单的React组件为什么会多次渲染?

部署到github pages时请求路径错误

从服务器获取数据时未定义,错误非法调用

如何检索包含动态段的未解析路径?

导航到屏幕时,react 本机上下文状态变为未定义

在 redux 工具包中使用 dispatch 发送多个操作

理解 React 中的 PrevState

服务器端分页未按预期工作

将 C# Razor 条件块转换为 React.js 代码