【发布时间】:2023-01-13 16:18:23
【问题描述】:
React 的一个常见知识是,如果我们不使它们同步,则由 props 初始化状态是不好的。这被认为很好:
import { useState, useEffect } from 'react';
export default function MyInput({ initialValue }) {
const [value, setValue] = useState(initialValue);
useEffect(
() => setValue(initialValue),
[initialValue]
);
return (
<>
<h1>The value is {value}</h1>
<input
type="text"
value={value}
onChange={event => setValue(event.target.value)}
/>
</>
);
}
但是,如果我实际上不想在 initialValue 更改时更新值并想删除此处的 useEffect() 怎么办?它强烈反对 React 哲学吗?这对我来说很有意义,因为我实际上不想在其他东西更改作为 initialValue 传递的值时更新此输入值。我不希望用户在发生这种情况时丢失他们的输入。
有多糟糕?
【问题讨论】:
-
用任何东西初始化 state 都是完全没问题的,props 如果需要的话。反模式正在同步它。
-
@EmileBergeron 我从来没有听说过将状态和道具同步称为反模式。
-
它通常被视为一种反模式,因为它使状态变得无用,因为 prop 应该按原样使用。在您的情况下,您不必将状态与道具同步,以便用户可以使用输入更新值。
-
这回答了你的问题了吗? React Hooks: handle multiple inputs
-
根据您的 cmet,我看到 XY problem,您在其中询问一些潜在的不良做法,但问题应该描述您的情况,minimal reproducible example 提供更多上下文。
标签: javascript reactjs use-state react-props