如何解决Redux useSelector返回未定义的嵌套值
我创建了一个客户类型
export interface ICustomer {
customer_code: string;
name: string;
}
并将其导入到我的reducer并在该文件中配置我的初始状态
import { createSlice,PayloadAction } from "@reduxjs/toolkit";
import {
ICustomer,} from "../types/createInvoice_types";
const InvoiceCustomerState: ICustomer[] = [];
export const createInvoiceCustomerSlice = createSlice({
name: "CustomerToInvoice",initialState: invoiceDetailsState,reducers: {
create: {
reducer: (state,{ payload }: PayloadAction<ICustomer>) => {
state.push(payload);
},prepare: (customer: Partial<ICustomer>) => ({
payload: customer,}),},remove: (state) => {
return InvoiceCustomerState;
},});
export const {
create: addCustomerToInvoice,remove: deleteCustomerToInvoice,} = createInvoiceCustomerSlice.actions;
以及我要使用它的组件中
import {
useSelector,RootStateOrAny,} from "react-redux";
const customer = useSelector(
(state: RootStateOrAny) => state.customerToInvoice
);
当我console.log(customer)
得到 [{"code": "123","name": "Cash Customer"}]
但是当我尝试console.log(customer.name)
时我得到undefined
我也尝试过这个,但是我仍然不确定
interface IRootState {
customer_code: string;
name: string;
}
const customer3 = useSelector((state: IRootState) => {
state.customerToInvoice.name;
});
console.log(customer3);
有人可以指出我做错了什么吗
解决方法
当我使用console.log(customer)时,我得到[{“ code”:“ 123”,“ name”:“ Cash Customer”}]
但是当我尝试console.log(customer.name)时,我无法定义
答案就在这两句话中。
当您console.log(customer)
清楚地显示customer === [{"code": "123","name": "Cash Customer"}]
时,它是其中包含单个对象的数组。
现在,如果您希望打印第一个元素的名称,则应该使用console.log(customer[0].name)
而不是console.log(customer.name)
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。