为什么 .map 函数在反应中不返回任何内容

丹尼尔·里希特

我有一个简单的反应演示,用于显示 websocket 消息,但 return 语句中的 .map 函数不返回任何内容。没有错误,也没有消息。谁能解释一下问题出在哪里?

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)
    )
}

现在返回语句中的问题:这里没有返回任何内容。

 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>
)

也许在收到 websocket 消息后没有重新渲染 return 语句?我希望任何人都有想法并可以解释这个问题。

德鲁里斯

问题

messages通过直接推入状态数组并将其保存回状态来改变状态数组。messages数组引用永远不会改变!React 使用浅对象引用相等来帮助确定何时应该更新 DOM。如果引用从不更新,则 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

  ...
}

解决方案

始终是正在更新的浅拷贝状态。使用功能状态更新从之前的状态更新

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
  ])

  ...
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

为什么.map()不返回任何内容?

如果javascript中的函数不返回任何内容,为什么?

为什么类中的函数不返回任何内容?

为什么javascript map函数返回undefined?

为什么map函数返回None?

为什么 dask 在 CUDA 函数上不返回任何内容?

main函数不返回任何内容。为什么?

为什么不将任何参数传递给map中的函数?

为什么在我的lambda函数上使用filter()和map()之类的函数时不返回任何值?

为什么套接字中的recv()函数不返回任何内容?

为什么Map不扩展Collection接口

为什么不Map#removeAll(Collection <?>)?

Java Map为什么不扩展Collection?

为什么Scipy的ndimage.map_coordinates对于某些数组不返回任何值或错误的结果?

为什么要使用map()函数?

为什么 todos.map 不是函数?

为什么空 unordered_map.find 不返回 end()?

为什么array.map不返回新数组?

为什么mutable.Map不扩展immutable.Map?

为什么Swift的类型检查系统允许返回类型的函数不返回任何内容?

为什么 JS Map 函数返回未定义?

为什么在反应中使用 map 函数在迭代中显示错误?

为什么Map不执行python 3中的功能

为什么我的递归二进制搜索函数不返回任何内容?

map() 函数中的 counter 不起作用,为什么?

Mongoose.findOne不返回任何内容,为什么?

Ajax请求不返回任何内容。为什么?

为什么PIG FILTER不返回任何内容?

为什么scanf()总是不返回任何内容?