Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - React re-render not showing updated state array

I am updating state(adding new object to state array) in event handler function.

const handleIncomingData = (data) => {
  setState(state => {
    var _state = state
    if (_state.someDummyStateValue === 1234) {
      _state.arr.push({ message: data.message })
    }
    return _state
  })
}

React.useEffect(() => {
  socket.on('data', handleIncomingData)
  return()=>{
    socket.off('data', handleIncomingData)
  }
},[])

I am updating state in this manner as event handler function is not having access to latest state values. console.log(state) shows updated state but after re-render newly added object is not displayed. Also when same event fires again previously received data is displayed but not the latest one. Is there something wrong with updating state in this manner?

question from:https://stackoverflow.com/questions/65870241/react-re-render-not-showing-updated-state-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Object in javascript are copied by reference (the address in the memory where its stored). When you do some thing like:

let obj1 = {}
let obj2 = obj1;

obj2 has the same reference as obj1.

In your case, you are directly copying the state object. When you call setState, it triggers a re-render. React will not bother updating if the value from the previous render is the same as the current render. Therefore, you need to create a new copy of your state.

Try this instead:

setState(prevValue => [...prevValue, {message: data.message}])

To better illustrate my point here's a codesandbox: https://codesandbox.io/s/wild-snowflake-vm1o4?file=/src/App.js


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...