简体   繁体   English

为什么.map function 没有反应

[英]Why does .map function return nothing in react

i have a simple react demo where to show websocket messages, but the.map function inside return statements returns nothing.我有一个简单的反应演示,其中显示 websocket 消息,但.map function 内部返回语句不返回任何内容。 No errors and no messages.没有错误,也没有消息。 Can anyone explain where the problem is in here?谁能解释问题出在哪里?

const [messages, setMessages] = React.useState([])

//push the websocket messages response to const messages
const addMessage = (message) => {
    let n = messages;
    let d = message;
    n.push(d);
    setMessages(n)

    //the following both works as expected
    messages.map((item) => {
        console.log('message', item.message)
    })
    messages.map((message, index) =>
        console.log(message,index)
    )
}

Now the problem in return statement: Here was nothing returned.现在返回语句中的问题:这里没有返回任何内容。

 return (
   <div>
     {
       messages.map(function(message, index){
         return (<p id={'t'+index}>{message.message}</p>)
       }),

       messages.map((message, index) =>{
         return (<p id={'z'+index}>{message.message}</p>)
       })
     }
  </div>
)

Maybe the return statement is not rerendered after receiving websocket message?可能收到 websocket 消息后,return 语句没有重新渲染? I hope anyone have an idea and can explain the problem.我希望任何人都有一个想法并可以解释这个问题。

Issue问题

You are mutating the messages state array by pushing directly into it and saving it back into state.您正在改变messages state 数组,方法是直接推入它并将其保存回 state。 The messages array reference never changes. messages数组引用永远不会改变。 React uses shallow object reference equality to help determine when the DOM should be updated. React 使用浅 object 引用相等来帮助确定何时应该更新 DOM。 If the reference never updates then React bails on rerendering.如果引用永远不会更新,那么 React 将放弃重新渲染。

const [messages, setMessages] = React.useState([])

//push the websocket messages response to const messages
const addMessage = (message) => {
  let n = messages; // <-- reference to state
  let d = message;
  n.push(d);        // <-- state mutation
  setMessages(n).   // <-- saved back into state

  ...
}

Solution解决方案

Always shallow copy state that is being updated.始终浅拷贝 state 正在更新。 Use a functional state update to update from the previous state使用功能 state 更新从以前的 state 更新

const [messages, setMessages] = React.useState([])

//push the websocket messages response to const messages
const addMessage = (message) => {
  setMessages(messages => [
    ...messages, // <-- shallow copy messages array
    message,     // <-- and append new message
  ])

  ...
}

I think you should try:我认为你应该尝试:

let n = [...messages];

instead反而

let n = messages;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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