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

使用Material UI ToggleButton时遇TypeError: setView不是函数问题求助

解决Material UI ToggleButton点击时报错TypeError: setView is not a function的问题

我使用Material UI的ToggleButton实现视图切换,点击按钮时触发报错:TypeError: setView is not a function,相关代码如下:

状态声明与处理函数:

const [view, setView] = useState("view 1")

const handleViewChange = (value) => {
  console.log("this is the value", value.target.value)
  setView(value.target.value)
}

ToggleButtonGroup的JSX代码:

<ToggleButtonGroup
   value={view}
   exclusive
   aria-label="Platform"
   onChange={handleViewChange}
>
  <ToggleButton value="view 1">View 1</ToggleButton>
  <ToggleButton value="view 2">View 2</ToggleButton>
</ToggleButtonGroup>

视图渲染逻辑:

{view === "view 1" ?
  (<div>
    <Grid container spacing = {2}>
      {view1_cards.map((card, index) => (
        <Grid item xs={6}>
          <Card key={index} title={card.title} content={card.content}>
            <CardContent>
              <h2>{card.title}</h2>
              <p>{card.content}</p>
            </CardContent>
          </Card>
        </Grid>
      ))}
    </Grid>
  </div>) :
  <div></div>
}

问题原因分析

  1. ToggleButtonGroup onChange回调参数错误:Material UI的ToggleButtonGroup组件的onChange回调函数签名为(event: React.MouseEvent<HTMLElement>, value: T) => void,第一个参数是事件对象,第二个参数才是选中的按钮值。当前处理函数只接收了第一个参数,并且错误尝试从value.target.value取值,这会导致参数解构错误,进而引发状态更新函数调用异常。
  2. 未处理exclusive模式下的null值:当开启exclusive模式时,点击已选中的按钮会返回null,直接调用setView(null)可能引发后续渲染逻辑的问题。

解决方案

修改handleViewChange函数,正确接收回调参数,并处理null值:

const handleViewChange = (event, newValue) => {
  // 仅当新值不为null时更新状态
  if (newValue !== null) {
    setView(newValue);
  }
}

另外检查以下潜在问题:

  • 确认useState的声明没有语法错误,比如是否正确写成const [view, setView] = useState("view 1"),避免变量名拼写错误。
  • 确保setView没有在其他代码中被意外覆盖或重新赋值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:45:29