React setState not updating state

前端 未结 9 640
慢半拍i
慢半拍i 2020-11-22 05:41

So I have this:

let total = newDealersDeckTotal.reduce(function(a, b) {
  return a + b;
},
0);

console.log(total, \'t         


        
相关标签:
9条回答
  • 2020-11-22 05:54

    setState() is usually asynchronous, which means that at the time you console.log the state, it's not updated yet. Try putting the log in the callback of the setState() method. It is executed after the state change is complete:

    this.setState({ dealersOverallTotal: total }, () => {
      console.log(this.state.dealersOverallTotal, 'dealersOverallTotal1');
    }); 
    
    0 讨论(0)
  • 2020-11-22 05:57

    The setstate is asynchronous in react, so to see the updated state in console use the callback as shown below (Callback function will execute after the setstate update)

    The below method is "not recommended" but for understanding, if you mutate state directly you can see the updated state in the next line. I repeat this is "not recommended"

    0 讨论(0)
  • 2020-11-22 05:58

    I had an issue when setting react state multiple times (it always used default state). Following this react/github issue worked for me

    const [state, setState] = useState({
      foo: "abc",
      bar: 123
    });
    
    // Do this!
    setState(prevState => {
      return {
        ...prevState,
        foo: "def"
      };
    });
    setState(prevState => {
      return {
        ...prevState,
        bar: 456
      };
    });
    
    0 讨论(0)
  • 2020-11-22 06:02

    In case of hooks, you should use useEffect hook.

    const [fruit, setFruit] = useState('');
    
    setFruit('Apple');
    
    useEffect(() => {
      console.log('Fruit', fruit);
    }, [fruit])
    
    0 讨论(0)
  • 2020-11-22 06:04

    Using async/await

    async changeHandler(event) {
        await this.setState({ yourName: event.target.value });
        console.log(this.state.yourName);
    }
    
    0 讨论(0)
  • 2020-11-22 06:08

    just add componentDidUpdate(){} method in your code, and it will work. you can check the life cycle of react native here:

    https://images.app.goo.gl/BVRAi4ea2P4LchqJ8

    0 讨论(0)
提交回复
热议问题