javascript 数据被提取并存储到redux中,但在访问时未定义

nwlls2ji  于 2023-02-11  发布在  Java
关注(0)|答案(2)|浏览(90)

我正在我的redux操作创建器中进行api调用,将这些数据存储到我的redux状态中,但是当尝试使用useSelector访问时,得到未定义的。无法理解我做错了什么。这里的任何帮助都是很好的。我正在使用redux工具包。附加reducer、操作创建器、组件、redux状态快照(来自redux开发工具和调试日志)
注:appID将来自路径参数,但现在我将其硬编码在我的建议受众中,如果我注解掉导致问题的{app.name},则我的redux状态将正确加载,快照已附加

观察结果:如果我正在对建议的受众进行任何更改并保存,那么我将获得价值,但当重新加载它2 - 3次时,错误再次出现。

//apps slice to store apps
import { createSlice } from "@reduxjs/toolkit";
import _ from "lodash";

const appsSlice = createSlice({
  name: "apps",
  initialState: {},
  reducers: {
    appSuccess(state, action) {
      const apps = _.keyBy(action.payload.data, "uuid");
      return apps;
    },
  },
});

export const appsAction = appsSlice.actions;
export default appsSlice.reducer;
//ui-slice to store app data
import { createSlice } from "@reduxjs/toolkit";

const uiSlice = createSlice({
  name: "ui",
  initialState: { appId: null, orgId: null },
  reducers: {
    setAppId(state, action) {
      state.appId = action.payload;
    },
  },
});

export const uiAction = uiSlice.actions;
export default uiSlice.reducer;
//App.js
import logo from "./logo.svg";
import "./App.css";
import PageHeader from "./components/PageHeader";
import SuggestedAudiences from "./components/SuggestedAudiences";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { uiAction } from "./components/store/ui-slice";
import { appsAction } from "./components/store/apps-slice";
import { fetchApps } from "./components/store/apps-action";

function App() {
  const dispatch = useDispatch();

  const appID = "52f14657d6c765401a2d7d4-41dfb38a-4262-11e3-9166-005cf8cbabd8";

  useEffect(() => {
    dispatch(uiAction.setAppId(appID));
    dispatch(fetchApps());
  }, []);

  return (
    <>
      <PageHeader />
      <SuggestedAudiences />
    </>
  );
}

export default App;
//Suggested Audiences
import React, { useEffect } from "react";

import { fetchApps } from "./store/apps-action";
import { useDispatch, useSelector } from "react-redux";
import { uiAction } from "./store/ui-slice";

const SuggestedAudiences = (props) => {
  const dispatch = useDispatch();

  const appId = useSelector((state) => state.ui.appId);
  const app = useSelector((state) => state.apps[appId]);

  return (
    <>
      <div>Suggested Audiences 🚀</div>
      {app.name}
    </>
  );
};

export default SuggestedAudiences;

j0pj023g

j0pj023g1#

尝试将此行const app = useSelector((state) => state.apps[appId]);更改为此行const app = useSelector((state) => state?.apps[appId]);我对此不确定

vsnjm48y

vsnjm48y2#

通过执行{app &&app.name}或{app?.name}也可以修复此问题。如果有人可以帮助我了解发生此问题的原因,以及是否有其他方法可以修复此问题,使未定义不会出现在第一位,请将其保持打开状态。

相关问题