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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…