简体   繁体   English

如何在React Hooks中的对象内部的方法内访问对象属性

[英]How to access the Object property within the method inside the Object in React Hooks

I am new to React hooks and been playing with the useState function lately.. In vanilla javascript this code works: 我是React钩子的新手,最近一直在使用useState函数。.在普通javascript中,此代码有效:

const state = {
  firstname: "John",
  lastname: "Doe",
  greeting: function(){
     return sayHello(this.firstname,this.lastname)
  }
}

const sayHello = (fname,lname)=>{
  return `Hello i'm ${fname} ${lname}, nice to meet you!`;
}

console.log(state.greeting()); //outputs "Hello i'm John Doe, nice to meet you!"

But with React hooks: 但是使用React挂钩:

const [state,setState] = useState({
  firstName: "John",
  lastName: "Doe",
  greeting: function(){
    return sayHello(this.firstName,this.lastName)
  }
})

const sayHello = (fname,lname) => console.log(`Hello i'm ${fname} ${lname}, nice to meet you!`);

const { firstName, lastName, greeting } = state;
return (
    <div>
        <button className="btn" onClick={greeting()}>Greet</button>
    </div>
)

I get an error saying: "Cannot read property 'firstName' of undefined", and i also get [object object] if i just use the "firstName" and "lastName" within the method without the "this" keyword. 我收到一条错误消息:“无法读取未定义的属性'firstName'”,并且如果我仅在方法中使用“ firstName”和“ lastName”而不使用“ this”关键字的话,也会得到[object object]。 How can i access the variables? 如何访问变量?

First of all, you're not calling the greeting method, you should call it in order to get your code working. 首先,您没有调用greeting方法,应该调用它以使代码正常工作。

Second, you should keep your state as lean as possible, so rethink twice before assigning a method to your state, there's a better place to place it in. 其次,您应该保持状态尽可能的精简,因此在为状态分配方法之前要三思而后行,这是放置它的更好位置。

const [firstName, setFirstName] = useState('John');
const [lastName, setLastName] = useState('Doe');

const greeting = () => {
  console.log(`Hello i'm ${firstName} ${lastName}, nice to meet you!`);
}

Then somewhere in your code call greeting() . 然后在代码中的某处调用greeting()

As you can see, we're assigning the firstName and lastName variables with their initial values and their respective setters thanks to react hooks, so you can call them directly in your code. 如您所见,由于react挂钩,我们为firstNamelastName变量分配了它们的初始值和各自的设置器,因此您可以在代码中直接调用它们。

console.log(`Hi, my name is ${firstName}`) // Hi, my name is John

And if you run setFirstName('David') and after that, you run again: 并且如果您运行setFirstName('David')并在此之后再次运行:

console.log(`Hi, my name is ${firstName}` // Hi, my name is David

You will get the updated version of firstName , that's better isn't? 您将获得firstName的更新版本,这更好吗?

The only possibility for the error to occur is that greeting is used with wrong context, eg as a callback. 发生错误的唯一可能性是,在错误的上下文中使用了greeting ,例如作为回调。 This can be fixed by hard-coding it to use correct object: 可以通过对其进行硬编码以使用正确的对象来解决此问题:

  ...
  greeting: () => sayHello(state.firstname, state.lastname)
  ...

React and React hooks encourage the use of FP instead of OOP. React和React钩子鼓励使用FP而不是OOP。 If there are no reasons to keep greeting method as a part of the state, it can be: 如果没有理由将greeting方法保留为状态的一部分,则可以是:

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

const { firstName, lastName } = state;
const greeting = () => sayHello(firstName, lastName);

useCallback is not necessary but it may help in some cases: useCallback不是必需的,但在某些情况下可能会有所帮助:

const greeting = useCallback(() => sayHello(firstName, lastName), [firstName, lastName]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM