我们使用reactjs和Typescript进行开发。在我们的一个组件中,我们使用如下两个函数。
interface SysUser {
id: number;
name: string;
group: string;
}
const getUsers = (userGroup: string): { listUsers: SysUser[] } => {
let listUsers: SysUser[] = [];
listUsers.push({ id: 1, name: "John", group: userGroup });
listUsers.push({ id: 2, name: "David", group: userGroup });
console.log("listUsersinFunction", JSON.stringify(listUsers));
return { listUsers };
}
const showUsers = () => {
let sysUsers = getUsers("SYS");
console.log("listUsersafterFunction", JSON.stringify(sysUsers));
//business logic
}
getUsers 里面的控制台日志是
listUsersinFunction [{"id":1,"name":"John","group":"SYS"},{"id":2,"name":"David","group":"SYS"}]
而控制台登录 showUsers 是
listUsersafterFunction {"listUsers":[{"id":1,"name":"John","group":"SYS"},{"id":2,"name":"David","group":"SYS"}]}
期望两者应该相同。但 showUsers 中的对象是完全不同的对象。我们在这里做错了什么?
如有任何帮助,我们将不胜感激。谢谢
修改您的
const showUsers = () => {
const { listUsers } = getUsers("SYS"); /* <-- modify how you access the return value from getUsers method */
console.log("listUsersafterFunction", JSON.stringify(listUsers));
//business logic
}
您正在
Object
方法中返回 getUsers
。
return { listUsers }
。返回值是 Object
你会得到类似 {"listUsers":[{"id":1,"name":"John","group":"SYS"},{"id":2,"name":"David","group":"SYS"}]}
.
如果您只需要 listUsers 数组的值,您可以使用对象解构,如
const { listUsers } = getUsers("SYS");