简体   繁体   中英

Proper way to append to a React array state using React Hooks?

I'm trying to implement a simple history of message in React.

I want to use a useEffect Hook that will depend on the sentMessage state. Upon trigger of the effect, I want to append to my history of messages the new value of the sent message.

However, using setHistoryState((prevValue) => prevValue.push(sentMessage) is, if I understand well, not the right way to proceed since historyState is not in the dependencies.

What is the correct way to implement this ?

Is not necessary to have historyState in useEffect 's dependencies to call setHistoryState . So I think you could do something like:

useEffect(() => {
   setHistoryState(prevValue => [...prevValue, sentMessage]);
}, [sentMessage]);

This means that, every time sentMessage changes his value, new value will be pushed in historyState .

You could spread the existing history and create a new array with its values, adding a new element in the process.

// historyState is an array here
const [historyState, setHistoryState] = useState([1,2,3])

setHistoryState(history => [...history, newValue]);

https://codesandbox.io/s/cocky-browser-v8jp0

From what i see your problem may come frome the fact prevValue.push will mutate your state "prevValue". This is not a recomanded way to manipulate states.

You could change your state this way =>

setHistoryState((prevValue) => ([...prevValue, sentMessage]))

Have a look to "avoid+mutations+js" on google.

You make a copy of its like that

setHistoryState((prevValue) => {
    const value = JSON.parse(JSON.stringiy(prevValue) 
    value.push(sentMessage)
    return value
}

You can try another deep copy ways instead using JSON

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM