Javascript 访问;这";React状态对象中的关键字

Javascript 访问;这";React状态对象中的关键字,javascript,node.js,reactjs,typescript,state,Javascript,Node.js,Reactjs,Typescript,State,我有一个usestate对象,如下所示: const [state, setState] = React.useState({ firstName: "John", lastName: "Doe", id: "12345", getFullName():any { return `${this.firstName} ${this.lastName}`; }, }); ...

我有一个
usestate
对象,如下所示:

const [state, setState] = React.useState({
    firstName: "John",
    lastName: "Doe",
    id: "12345",
    getFullName():any {
      return `${this.firstName} ${this.lastName}`;
    },
  });


...

return (
  <button onClick={() => console.log(state.getFullName())}></button>
)
此外,如果忽略此TS警告,我仍然会得到一个
无法读取未定义的属性“firstName”的错误


如何使其工作?

问题在于函数
useState
,它可以接受initialState或生成它的函数:

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

还考虑使用IIFE构造初始状态:

const initialState = ((firstName, lastName) => ({
    firstName,
    lastName,
    id: "12345",
    getFullName():string {
    return `${firstName} ${lastName}`;
  },
}))('John', 'Doe');

问题在于函数
useState
,它可以接受initialState或生成它的函数:

function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];

还考虑使用IIFE构造初始状态:

const initialState = ((firstName, lastName) => ({
    firstName,
    lastName,
    id: "12345",
    getFullName():string {
    return `${firstName} ${lastName}`;
  },
}))('John', 'Doe');

您可以将其放入单独的函数中,在功能组件中访问“this”是个坏主意

const [state, setState] = React.useState({
firstName: "John",
lastName: "Doe",
id: "12345"});

const getFullName = () => {
    return `${state.firstName} ${state.lastName}`
}

您可以将其放入单独的函数中,在功能组件中访问“this”是个坏主意

const [state, setState] = React.useState({
firstName: "John",
lastName: "Doe",
id: "12345"});

const getFullName = () => {
    return `${state.firstName} ${state.lastName}`
}

请告诉我们您如何调用该方法我在单击按钮时调用该方法。请告诉我们您如何调用该方法我在单击按钮时调用该方法。是的,但我仍然在
中得到TSLint错误。firstName
就像我在上面发布的一样,这将不起作用。1.该函数仅在初始渲染时执行,因此getFullName()将在第一个setState 2上被擦除。无论如何,“this”键很可能是指窗口对象,this.firstName仍然是未定义的,但我仍然在
this.firstName
中得到TSLint错误,就像我在上面发布的那样,这将不起作用。1.该函数仅在初始渲染时执行,因此getFullName()将在第一个setState 2上被擦除。无论如何,“this”键很可能是指窗口对象,this.firstName仍将是未定义的