React中如果两个元素同时尝试访问和更新状态,应该如何处理?

huangapple go评论63阅读模式
英文:

How should two elements be handled in React if they are simultaneously attempting to access and update the state?

问题

我有两个共享相同状态的元素。我希望在一个元素中进行更改,这些更改需要反映在另一个元素中,反之亦然。我的当前代码不允许我运行,也不会抛出任何错误。请帮助我解决这个问题。以下是您的代码审查。

渲染组件:

<Editors name={"Hello"} />

实际组件:

import * as React from 'react';
import { useEffect, useState } from 'react';

export interface IName {
  name: string;
}

function Editors(props: IName) {
  const [name, setName] = useState('');

  useEffect(() => {
    setName(props.name);
  }, [props, name]);

  return (
    <React.Fragment>
      <div>
        <input value={name} onChange={(e) => setName(e.target.value)} />
      </div>

      <br />

      <div>
        <textarea
          value={name}
          onChange={(e) => setName(e.target.value)}
        ></textarea>
      </div>
    </React.Fragment>
  );
}

export default Editors;

您可以点击以下链接查看示例:https://stackblitz.com/edit/react-ts-daok8m?file=Editors.tsx,App.tsx

英文:

I have two elements that share the same state. I want to make changes in one element that need to be reflected in another element, and vice versa. My current code is not allowing me to run and is not throwing any errors. Please help me fix the issue. Below is the code for your review.

Rendering component:

&lt;Editors name={&quot;Hello&quot;} /&gt;

Actual Component:

import * as React from &#39;react&#39;;
import { useEffect, useState } from &#39;react&#39;;

export interface IName {
  name: string;
}

function Editors(props: IName) {
  const [name, setName] = useState(&#39;&#39;);

  useEffect(() =&gt; {
    setName(props.name);
  }, [props, name]);

  return (
    &lt;React.Fragment&gt;
      &lt;div&gt;
        &lt;input value={name} onChange={(e) =&gt; setName(e.target.value)} /&gt;
      &lt;/div&gt;

      &lt;br /&gt;

      &lt;div&gt;
        &lt;textarea
          value={name}
          onChange={(e) =&gt; setName(e.target.value)}
        &gt;&lt;/textarea&gt;
      &lt;/div&gt;
    &lt;/React.Fragment&gt;
  );
}

export default Editors;

stackblitz link to see in action https://stackblitz.com/edit/react-ts-daok8m?file=Editors.tsx,App.tsx

答案1

得分: 0

useEffect的依赖中移除name应该能解决问题。

useEffect(() => {
  setName(props.name);
}, [props]);
英文:

removing name from the useEffect dependence should do the trick

useEffect(() =&gt; {
  setName(props.name);
}, [props]);

huangapple
  • 本文由 发表于 2023年3月1日 09:29:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75598827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定