简体   繁体   中英

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:

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:

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. 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.

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() .

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.

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

And if you run setFirstName('David') and after that, you run again:

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?

The only possibility for the error to occur is that greeting is used with wrong context, eg as a callback. 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. If there are no reasons to keep greeting method as a part of the state, it can be:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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