首页 > 解决方案 > React Native 错误,Redux:键“nav”的切片缩减器在初始化期间返回未定义

问题描述

使用 React Native 进行超级克隆,在创建应用程序的同时设置 Redux,Metro 捆绑器返回以下错误:

Error: The slice reducer for key "nav" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.
at node_modules\react-native\Libraries\LogBox\LogBox.js:149:8 in registerError
......

Invariant Violation: "main" has not been registered. This can happen if:
    * Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
    * A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.

.....

这是 App.js

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Provider } from 'react-redux';
import { store } from './store';

// 1. Set up redux - done
// 

export default function App() {
  return (
    <Provider store={store}>
    <View style={styles.container}>
      <Text>Uber</Text>
    </View>
    </Provider>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

这是 navSlice.js

import { createSlice } from "@reduxjs/toolkit";

const innitialState = {
    origin: null,
    destination: null,
    travelTimeInformation: null,
}

export const navSlice = createSlice({
    name:"nav",
    innitialState,
    reducer: {
        setOrigin: (state, action) =>{
            state.origin = action.payload;
        },
        setDestination: (state, action) =>{
            state.destination = action.payload;
        },
        setTravelTimeInformation: (state, action) =>{
            state.travelTimeInformation = action.payload;
        },
        
    }
});

export const { setOrigin, setDestination, setTravelTimeInformation } = navSlice.actions;

// Selectors

export const selectOrigin = (state) => state.nav.origin;
export const selectDestination = (state) => state.nav.destination;
export const selectTravelTimeInformation = (state) => state.nav.travelTimeInformation;

export default navReducer = navSlice.reducer;

这是 Store.js

import { configureStore } from "@reduxjs/toolkit";
import navReducer from "./slices/navSlice";

export const store = configureStore({
    reducer: {
        nav: navReducer,
    },
});

我收到这些错误的原因是什么?我怎样才能解决这个问题?我如何设置 redux 有问题吗?

标签: react-nativereact-reduxmetro-bundler

解决方案


将 navslice 中的拼写更改为 reducers 并重新启动模拟器


推荐阅读