【问题标题】:How to initialize hook state . All state elements are missing如何初始化钩子状态。缺少所有状态元素
【发布时间】:2021-06-29 20:26:31
【问题描述】:

这个组件的行为有些奇怪

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

当这个状态

  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 要么没有依赖数组,要么每次渲染时有一个依赖项发生变化。

【问题讨论】:

  • 只需传递一个空的依赖数组,如下所示 useEffect(() => { setState({qualification: props.profile.qualification, twitter: props.profile.twitter, }); }, []) ;

标签: javascript reactjs react-hooks


【解决方案1】:

您的 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 中,你应该直接使用传递的道具。

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

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

【讨论】:

    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2022-01-19
    • 2023-01-10
    相关资源
    最近更新 更多