You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React问题:状态变更时Material UI Drawer内容未渲染

问题排查与解决

嘿,我一眼就揪出问题啦!你的map()回调函数里没有返回JSX元素,这就是动态生成的ListItem不显示的核心原因。

先看你这段代码:

{this.props.notifications.map((n, key) => { 
  <ListItem key={key}> 
    <ListItemIcon> 
      <Info/> 
    </ListItemIcon> 
    <ListItemText inset primary={n.header} secondary={n.message}/> 
  </ListItem> 
})}

当箭头函数用大括号{}包裹代码块时,必须显式写return语句来返回要渲染的内容,不然默认会返回undefined。这样map()就会生成一个全是undefined的数组,自然看不到任何动态渲染的列表项。

两种简单修正方案:

  1. 添加显式return:
{this.props.notifications.map((n, key) => { 
  return (
    <ListItem key={key}> 
      <ListItemIcon> 
        <Info/> 
      </ListItemIcon> 
      <ListItemText inset primary={n.header} secondary={n.message}/> 
    </ListItem> 
  )
})}
  1. 去掉大括号,用隐式return:
    如果你的回调逻辑只有返回JSX这一步,直接去掉大括号,箭头函数会自动返回后面的表达式:
{this.props.notifications.map((n, key) => (
  <ListItem key={key}> 
    <ListItemIcon> 
      <Info/> 
    </ListItemIcon> 
    <ListItemText inset primary={n.header} secondary={n.message}/> 
  </ListItem> 
))}

补充说明:

静态ListItem能正常显示,是因为它直接作为JSX元素被返回,没有经过map()的处理。而动态生成的部分因为map()没返回有效元素,所以被忽略了。这个问题和Drawer组件本身无关,只是箭头函数的语法细节没注意到~

内容的提问来源于stack exchange,提问作者mabu1981

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:25:27