如何解决 React 中过多的重新渲染错误

How to solve too many re-renders error in react

我正在尝试在反应中进行切换,如果状态为 false 则呈现一个特定图标,如果状态为 true 则呈现另一个图标...我正在尝试在单击按钮时更改状态..但是我收到此错误:

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

这是错误给出组件的 javascript:

const [wantsPassword, setWantsPassword] = useState(false)

这是 JSX:

   <IconButton onClick={setWantsPassword(!wantsPassword)}  >
      {wantsPassword?<VisibilityOffIcon/>:<VisibilityIcon />}
    </IconButton>

我哪里错了?

问题是您在渲染 上调用设置函数 ,而不是在单击时调用。您需要使 onClick 成为函数,而不是函数调用:

   <IconButton onClick={() => setWantsPassword(!wantsPassword)}  >

您在每次渲染时调用 onClick 中的函数 <IconButton onClick={setWantsPassword(!wantsPassword)} >

改为:

<IconButton onClick={() => setWantsPassword(!wantsPassword)}>

您不应该在 onClick 中执行函数。而是像下面这样:-

<IconButton onClick={() => setWantsPassword(!wantsPassword)}  >

你应该像这样使用箭头函数:

<IconButton onClick={() => setWantsPassword(!wantsPassword)}  >