P粉7295188062023-08-18 14:21:45
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:
hero
is not used here. I guess the hook should also return that value so it can be used. 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 }; }