开发者问题收集

react/redux app-TypeError:无法读取未定义的属性“用户”

2021-03-15
5548

我正在创建一个 React 应用,从 redux 获取数据。我在浏览器中遇到了以下错误消息。请检查并告诉我我遗漏了什么。

我正在使用 create-react-app redux-toolkit 安装模板来创建应用

这是我的 app.js :

import React from "react";
import { useSelector } from "react-redux";
import "./App.css";
import { selectUser } from "./features/userSlice";
import Header from "./components/Header";
import Sidebar from "./components/Sidebar";
import Feed from "./components/Feed";
import Login from "./components/Login";

function App() {
    const user = useSelector(selectUser);
    
    return (
        <div className="App">
            <Header />
            { !user ? (
                <Login />
            ) : (
                <div className="main_content">
                    <Sidebar />
                    <Feed />
                </div>
            )}
        </div>
    );
}

export default App;

下面你可以找到 redux Reducer 和 Action

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

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    user: null,
  },
  reducers: {
    login: (state, action) => {
      state.value = action.payload
    },
    logout: (state, action) => {
      state.user = null
    }
  },
});

export const { login, logout } = userSlice.actions;

export const selectUser = (state) => state.user.user;

export default userSlice.reducer;

下面是错误的屏幕截图。我在运行应用时遇到错误

在此处输入图片描述

1个回答

此示例可供您使用,请确保您正确配置了商店。您应该将其分成响应文件。

import React from "react";
import { combineReducers, createStore, createSlice } from "@reduxjs/toolkit";
import { connect, Provider, useDispatch, useSelector } from "react-redux";

// your part
const userSlice = createSlice({
  name: "user",
  initialState: {
    user: null
  },
  reducers: {
    login: (state, action) => {
      state.user = action.payload;
    },
    logout: (state, action) => {
      state.user = null;
    }
  }
});

const { login, logout } = userSlice.actions
const selectUser = (state) => state.user.user;

// what I added
const reducer = combineReducers({
  user: userSlice.reducer
});

const store = createStore(reducer);

const Main = (props) => {
  const dispatch = useDispatch() // I used this to check if reducers work
  const user = useSelector( selectUser )

  return (
    <div onClick={ () => { dispatch(login({name: "Adam"})) }}>
        { !user ? "LOGIN" : "DASHBOARD "}
    </div>
  )
}

const mapStateToProps = (state) => ({
  user: state.user
});

const Container = connect(mapStateToProps, { login, logout })(Main);

function App() {
  return (
    <Provider store={store}>
      <Container/>
    </Provider>
  );
}

export default App;
Kishieel
2021-03-15