简体   繁体   English

如何立即为 function React 更新 useState

[英]How do I update useState immidiatly for function React

I have created a function to calculate the winner between the two selected pokemon.我创建了一个 function 来计算两个选定的神奇宝贝之间的赢家。 However, instead of using the newly selected option, it is using the previously selected option.但是,它没有使用新选择的选项,而是使用以前选择的选项。 It has been brought to my attention that this is because useState is not updating immediately so how would I go about fixing this?我注意到这是因为 useState 没有立即更新,所以我 go 如何解决这个问题?

Here is my winner function:这是我的赢家 function:

function selectedWinner(){

console.log(pokemonName+' '+pokeOneTotal);
console.log(pokemonName2+' '+pokeTwoTotal);
if(pokeOneTotal>pokeTwoTotal){
    setPokemonWinner(pokemonName);
}else if(pokeOneTotal<pokeTwoTotal){
    setPokemonWinner(pokemonName2);
}else{
    setPokemonWinner("Draw");
}

} }

I have set it so that it is called in the different select functions, which are on click functions, here is one as an example:我已经设置它以便在不同的 select 函数中调用它,这些函数是点击函数,这里是一个例子:

 function optionOneSelected(){
   
    console.log('selected');
    axios.get('https://pokeapi.co/api/v2/pokemon/'+ pokemonOne.current.value)
    .then((res)=>{

      let data=res.data;
      console.log(data);

      let type = data.types[0].type.name;
      let id = data.id;
      let height= data.height;
      let weight = data.weight;
      let name = data.forms[0].name;
      let hp = data.stats[0].base_stat;

      //console.log(type)

      setPokemonType(type);
      setPokemonId(id);
      setPokemonHeight(height);
      setPokemonWeight(weight);
      setPokemonName(name);
      setPokemonHp(hp);

        let sum=0;
        sum= data.stats[0].base_stat+ data.stats[1].base_stat+ data.stats[2].base_stat+ data.stats[3].base_stat+data.stats[4].base_stat+data.stats[5].base_stat;
        setPokeOneTotal(sum);


          let pokemonOneDataList = [
            data.stats[0].base_stat, data.stats[1].base_stat, data.stats[2].base_stat, data.stats[3].base_stat,data.stats[4].base_stat,data.stats[5].base_stat
          ];

          let labels = [
              'hp', 'Attack', 'Defense', 'Special Attack', 'Special Defense', 'Speed'
          ];

          setPokemonOneData(pokemonOneDataList);
          setDataLabels(labels);
          selectedWinner();
          
      


    })

} }

You can call useEffect with pokeOneTotal and pokeTwoTotal as dependencies.您可以使用pokeOneTotalpokeTwoTotal作为依赖项调用useEffect Whenever pokeOneTotal or pokeTwoTotal updates, it will trigger useEffect每当pokeOneTotalpokeTwoTotal更新时,它会触发useEffect

useEffect(() => {
   if(pokeOneTotal>pokeTwoTotal){
       setPokemonWinner(pokemonName);
   }else if(pokeOneTotal<pokeTwoTotal){
       setPokemonWinner(pokemonName2);
   }else{
       setPokemonWinner("Draw");
   }
}, [pokeOneTotal, pokeTwoTotal])

Setting the state in React acts like an async function.在 React 中设置 state 就像一个异步 function。
Meaning that the when you set the state and put a console.log right after it, it will likely run before the state has actually finished updating.这意味着当您设置 state 并在其后放置一个console.log时,它可能会在 state 实际完成更新之前运行。

Which is why we have useEffect , a built-in React hook that activates a callback when one of it's dependencies have changed.这就是为什么我们有useEffect ,一个内置的 React 钩子,当它的一个依赖项发生变化时激活回调。

Example:例子:

useEffect(() => {
   // Whatever we want to do after the state has been updated.
}, [state])

This console.log will run only after the state has finished changing and a render has occurred.console.log仅在 state 完成更改并发生渲染后才会运行。

  • Note: "state" in the example is interchangeable with whatever state piece you're dealing with.注意:示例中的“状态”可与您正在处理的任何 state 部分互换。

Check the documentation for more info.查看文档以获取更多信息。

Either:任何一个:

  • Pass the new values to selectedWinner as arguments instead of reading from the state.将新值作为 arguments 传递给selectedWinner ,而不是从 state 读取。
  • Move the call to selectedWinner into a separate useEffect hook that has those state variables as dependencies (so it gets called when, and only when, any of them change).将对selectedWinner的调用移动到一个单独的useEffect挂钩中,该挂钩将那些 state 变量作为依赖项(因此当且仅当其中任何一个发生变化时才会调用它)。

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

相关问题 React.useState,不会更新。 如何执行 React useState 的即时更新? - React.useState, will not update. How do I perform a instant update of React useState? React hooks:如何使用 useState() 更新嵌套对象的状态? - React hooks: How do I update state on a nested object with useState()? 反应,我如何只更新使用 useState 钩子的 object 中的一个属性? - React, how do I update just one property in an object that uses the useState hook? 如何更新函数 React 返回的值(useState 实现) - How to update value returned by function React (useState implementation) Jest / React - 如何在 function 中测试 useState state 更新的结果 - Jest / React - How to test the results of useState state update in a function React useState() - 如何更新对象 - React useState() - how to update objects React useState:如何使用 onChange 更新我的 useState 输入和 OnClick 按钮? - React useState: How can I update my useState with onChange for input and OnClick for the button? 如何使用 useState 处理 API 响应以更新 state? - How do I handle an API response with useState to update a state? 如何在 React 中隐藏和显示带有 useState 或条件渲染的组件? - How do I hide and show components with useState or conditional rendering in React? 如何使用 forEach 将 React useState 推入数组? - How do I use forEach to push into an array with React useState?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM