UseState not re-rendering when updating nested object

前端 未结 1 365
轻奢々
轻奢々 2021-01-22 02:20

I\'m updating in useEffect by pushing data to the old state object and return it as a value.

This code is actually changing the _series variable from useState(), yet no

1条回答
  •  一个人的身影
    2021-01-22 03:07

    The problem is that when you change the state by modifying original state its value is updated at the original reference and hence react thinks that nothing has changed and hence it doesn't re-render, that is why it is expected that treat state as if it is immutable when you try to update state

     const { useState, useEffect } = React;
     const App = () => {
        
          const [_series, $series] = useState(()=>{
            let state = { data : { "name": "x", "columns": ["time", "value"], "points": [], "i" : 0}}
            for(let i=10; i >= 0; i--){state.data.points.push( [new Date(i)-(i*100), Math.round(Math.random()*100)])}
            return state;
          })
        
          useEffect(() => {
            const interval = setInterval(() => {
              $series(s => {
                return {
                    ...s,
                    data: {
                      ...s.data,
                      i: s.data.i + 1,
                      points: [...s.data.points.slice(1), [new Date(s.data.i*1000), Math.round(Math.sin(s.data.i/10)*50+50)]]
                    }
                }
              });
            }, 500);
          }, []);
        
        
            return(
            

    { JSON.stringify(_series.data) }

    ) } ReactDOM.render(, document.getElementById('app'));
    
    
    

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