如何初始化钩子状态。缺少所有状态元素

时间:2021-04-03 06:14:32

标签: javascript reactjs react-hooks

这个组件的行为有些奇怪

我尝试了几种实现方式。 但我仍然不知道如何正确初始化。

当这个状态

  const [state, setState] = useState({
      qualification: props.profile.qualification,
      twitter: props.profile.twitter,
  });

结果 console.log("AA01" + JSON.stringify(state)); AA01{} 不知何故,所有元素都不见了。

所以我把它们改成这样

  const [state, setState] = useState({
    qualification: "",
    twitter: "",
  });

  useEffect(() => {
    setState({
      qualification: props.profile.qualification,
      twitter: props.profile.twitter,
    });
  });


const handleChange = (event) => {
  console.log("AA01" + JSON.stringify(state));
  setState({ ...state, [event.target.id]: event.target.value });
};

const handleSubmit = (e) => {
  e.preventDefault();
  console.log("AA" + JSON.stringify(state));
  if (state.userName.length < 2) {
    return;
  }
  props.Update(users);
};

props 的数据被插入到状态但警告:最大更新深度超出。发生

警告:已超出最大更新深度。当组件在 useEffect 中调用 setState 时可能会发生这种情况,但 useEffect 要么没有依赖项数组,要么每次渲染时依赖项之一发生变化。

1 个答案:

答案 0 :(得分:2)

您的 useEffect 钩子缺少依赖项。如果没有,它会运行每个渲染并更新状态并触发另一个渲染。

在组件挂载时运行一次,使用空依赖数组

useEffect(() => {
  setState({
    qualification: props.profile.qualification,
    twitter: props.profile.twitter,
  });
}, []); // <-- run once on mount

在值更新时运行,使用填充的依赖数组

useEffect(() => {
  setState({
    qualification: props.profile.qualification,
    twitter: props.profile.twitter,
  });
}, [value]); // <-- run when value updates

不要在钩子回调中使用任何无条件更新的状态值,这也会导致渲染循环。

听起来您可能希望在 props 更新时更新本地状态(它们最初也可能像您所描述的那样为空),但这实际上反-模式在 React 中,你应该直接消费传递的 props。

但是,如果您仍然需要将它们存储在本地出于某种原因我认为这是您寻求的实现:

useEffect(() => {
  setState({
    qualification: props.profile.qualification,
    twitter: props.profile.twitter,
  });
}, [props.profile]); // <-- run with props.profile updates