In ReactJS, how to update useState's value from a separate file?
P粉237029457
P粉237029457 2023-08-17 19:46:21
0
1
394
<p>I'm trying to access and update the state of an object from two different files, if I use a local useState for each file then I can change it, but that doesn't work, </p> <p>I tried many different solutions, using custom hooks and local state but none of them solved my problem, I was stuck on this issue for about 5 hours and it was really driving me crazy, any help would be appreciated Greatful. </p> <p>I think the problem is that I'm trying to call the hook from the return statement, but I can't think of any alternative way to do it, since that's where it gets rendered. </p> <p>information.js:</p> <pre class="brush:php;toolbar:false;"><button class="active" onClick={() => useSetHero(hero)}></pre> <p>hero.js:</p> <pre class="brush:php;toolbar:false;">export const useSetHero = (newHero) => { const UpdateHero = () => { const [hero, setHero] = useState(newHero); setHero(newHero); }; return { UpdateHero }; }</pre> <p>The error message I am currently receiving is: React Hook "useHero" cannot be called in callback function. React Hooks must be called in a React function component or a custom React Hook function</p>
P粉237029457
P粉237029457

reply all(1)
P粉729518806

Define state for the hook itself, not the functions inside the hook. For example:

export const useHero = (initialHero) => {
  const [hero, setHero] = useState(initialHero);

  const UpdateHero = (newHero) => {
    setHero(newHero);
  };

  return { UpdateHero };
}

Also, please note the difference between initialHero and newHero here. The former is used to initialize the first state value when the hook is first called:

const { UpdateHero } = useHero(someValueHere);

The latter is used to update it to a new value when calling UpdateHero:

<button class="active" onClick={() => UpdateHero(hero)}>

Please note that in the above code you are not calling the hook directly in the markup. Hooks are called early in the component (and the same hooks are called in the same order on every render). The data and/or functions returned by the hook can then be used later.


Some notes:

  1. hero is not used here. I guess the hook should also return that value so it can be used.
  2. UpdateHero is redundant here, you can directly return setHero.

I'm assuming both of these issues are because this is just a very simplified example of what you are trying to do, the actual hook is more complex than this. However, if these issues are not considered, the above hook can be simplified to:

export const useHero = (initialHero) => {
  const [hero, UpdateHero] = useState(initialHero);

  return { hero, UpdateHero };
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!