如何使用带有 Typescript 的 useSelector 访问属性?

How do I access properties using useSelector with Typescript?

我正在尝试从状态访问联系人,但我总是获取整个状态。

我试过解构,但还是不行?

我的切片包含工具包和 thunk。

export interface Contact {
  name: string;
  phone: string;
  id: number;
}
export interface contactSliceState {
  contacts: Contact[];
  status: "idle" | "pending" | "succeeded" | "failed";
  loading: boolean;
}
const contacts: Contact[] = useSelector<contactSliceState, Contact[]>(  
    (state) => state.contacts  
  );
console.log("contacts", contacts) 
contacts:  
0: {name: "John", phone: "123012", id: 1}
1: {name: "Bill", phone: "653722", id: 2}
2: {name: "Tom", phone: "874932", id: 3}
loading: false
status: "succeeded" 

您似乎向 Typescript 编译器提供了有关状态形状的错误信息。由于 contacts 只是一个切片,您应该提供 root 状态的形状作为 useSelector 的第一个泛型。那么我相信它会更有意义:

const contacts = useSelector<RootState, Contact[]>(  
    (state) => state.contacts.contacts
  );

请注意,我所说的“根”状态只是包括所有切片的顶级状态(我假设 contacts 是顶级状态的键。