我创建了一个客户类型
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);
有人可以指出我做错了什么吗
答案 0 :(得分:1)
当我使用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)
。