英文:
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:
<Editors name={"Hello"} />
Actual Component:
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;
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(() => {
setName(props.name);
}, [props]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论