redux TypeError:无法读取null的属性(阅读“category_affiliation”)

ddarikpa  于 2023-08-05  发布在  Go
关注(0)|答案(1)|浏览(95)

我使用redux状态创建了一个登录函数,但问题是当我登录时,我得到一个错误消息。在我的Sidebar.jsx中。看起来,我不能立即呈现数据admin
TypeError:无法读取null的属性(阅读“category_affiliation”)
Sidebar.jsx

const Sidebar = () =>{

  const { admin } = useSelector((state) => state.admin);
  let techSuperAdmin = admin && admin.techAdmin ? admin.techAdmin : false;
  let techAdminCategory = admin && admin.category_affiliation ? admin.category_affiliation : null;
}

字符串
这是我的账号

const handleLogin = async (e) =>{
    e.preventDefault()
    try {
      await LoginUser(userAdmin, dispatch)
    } catch (error) {
      console.log(error)
    }
  }


MyAdminSlice.jsx

export const adminSlice = createSlice({
    name: 'admin',
    initialState: {
        admin: null,
        isFetching : false,
        isError: false,
        isSuccess: false,
        isUpdated: false,
        isMessage: "",
    },
    reducers: {
        resetState: (state) =>{
            state.admin = null;
            state.isFetching = false
            state.isError = false
            state.isSuccess = false
            state.isUpdated = false
            state.isMessage = ""

        },
        loginStart: (state)=>{
            state.isFetching = true;
            state.isError = false;
        },
        loginSuccess: (state, action) =>{
            state.isFetching = true;
            state.isSuccess = true;
            state.admin = action.payload,
            state.isMessage = "";
        },
        loginFailure: (state, action) =>{
            state.isSuccess = false;
            state.isFetching = false;
            state.isError = true;
            state.isMessage = action.payload;

        }, 
        logOut: (state) =>{
            state.admin = null;
        },

    }

})

export const {resetState, loginStart, loginSuccess, loginFailure, logOut } = adminSlice.actions;
export default adminSlice.reducer


编辑:
这是我得到的数据


的数据

ubby3x7f

ubby3x7f1#

你可以做下面的更改,因为在你的响应中没有category_affiliation
你可以添加可选的链接,如果键存在,则只读取它。
了解有关https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining更多信息

const Sidebar = () =>{

  const { admin } = useSelector((state) => state.admin);
  let techSuperAdmin = admin && admin?.techAdmin ? admin?.techAdmin : false;
  let techAdminCategory = admin && admin?.category_affiliation ? admin?.category_affiliation : null;
}

字符串

相关问题