使用 useState 为其分配 match.params 值时出现错误太多重新渲染

Getting error Too many re-renders when using useState to assign match.params value to it

这是导致问题的我的代码段。

function CreateU(props) {
const [uid, SetUid] = useState('');
const { id } = props.match.params;
  if (typeof (id) !== 'undefined') {
    SetUid(id);
  }
.
.
.
}

我收到错误消息太多重新渲染。 为了组件的可重用性,我不能直接使用 id , 我需要将它分配给 uid。 我还需要检查未定义,因为在某些情况下我不会在 link.

中传递 id
function CreateU(props) {
  const [uid, SetUid] = useState('');
  const { id } = props.match.params;

  useEffect(() => {
    if (typeof (id) !== 'undefined') {
      SetUid(id);
    }
  }, [id])

  .
  .
  .
}

您需要将对状态 setter 的调用包装在 useEffect 挂钩中。否则你会陷入无限循环,你在渲染时更新状态,这会触发重新渲染和另一个状态更新等等。