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

时间:2021-06-01 10:25:06

标签: reactjs react-router react-props use-state

这是导致问题的代码段。

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

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

1 个答案:

答案 0 :(得分:0)

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

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

  .
  .
  .
}

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