how to set state array using react hooks

前端 未结 5 858
情话喂你
情话喂你 2021-02-04 15:57

Thanks in advance. I have a state array as below.

I need to add an item to state array, I came across that we need not do state mutation. How do i set state with prevSta

相关标签:
5条回答
  • 2021-02-04 16:34

    More readable and cleaner solution it would be:

    Create a variable that holds a copy of the actual state:

    If state is an array and you need to add an element in it

    let newState = [...messages, 'Hi buddy'];
    setMessages(newState);
    

    If state is an object and you need to update a property in it

    let newState = Object.assign({}, message, {name: 'Michael Scott'});
    setMessages(newState);
    
    0 讨论(0)
  • 2021-02-04 16:39

    There is no real need to use the prevState, you could just do:

    setMessages([...messages, newMessage])
    
    0 讨论(0)
  • 2021-02-04 16:44

    To insert new element at the end of the list

    const addMessage = (newMessage) => setMessages(state => [...state, newMessage])
    

    To insert new element at the begining of the list

    const addMessage = (newMessage) => setMessages(state => [newMessage, ...state])
    
    0 讨论(0)
  • 2021-02-04 16:46

    setMessages(prevState => [...prevState, newMessage])

    0 讨论(0)
  • 2021-02-04 16:53

    Your state is an array so you will need to spread your previous state into a new array and add the new message using [...prevState, newMessage]

    What you try to do is return an object, because {} is a code block so you need to wrap it inside () if you return an object which is what you are trying to do

    setMessages(prevState => [...prevState, newMessage])
    
    0 讨论(0)
提交回复
热议问题