2 回答

TA贡献1875条经验 获得超3个赞
首先,您没有调用该greeting方法,应该调用它以使代码正常工作。
其次,您应该保持状态尽可能的精简,因此在为状态分配方法之前要三思而后行,这是放置它的更好位置。
const [firstName, setFirstName] = useState('John');
const [lastName, setLastName] = useState('Doe');
const greeting = () => {
console.log(`Hello i'm ${firstName} ${lastName}, nice to meet you!`);
}
然后在您的代码调用中的某处greeting()。
如您所见,由于react挂钩,我们为firstName和lastName变量分配了它们的初始值和各自的设置器,因此您可以在代码中直接调用它们。
console.log(`Hi, my name is ${firstName}`) // Hi, my name is John
如果运行setFirstName('David'),然后又运行,则再次运行:
console.log(`Hi, my name is ${firstName}` // Hi, my name is David
您将获得的更新版本firstName,这不是吗?

TA贡献1853条经验 获得超6个赞
发生错误的唯一可能性是在错误的greeting上下文中使用,例如作为回调。可以通过对其进行硬编码以使用正确的对象来解决此问题:
...
greeting: () => sayHello(state.firstname, state.lastname)
...
React和React钩子鼓励使用FP而不是OOP。如果没有理由将greeting方法保留为状态的一部分,则可以是:
const [state,setState] = useState({
firstName: "John",
lastName: "Doe"
});
const { firstName, lastName } = state;
const greeting = () => sayHello(firstName, lastName);
useCallback 并非必需,但在某些情况下可能会有所帮助:
const greeting = useCallback(() => sayHello(firstName, lastName), [firstName, lastName]);
添加回答
举报