这里的代码和框:https ://codesandbox.io/s/restless-haze-v01wv ? file =/ src/App.js
我有一个用户组件(简化后)如下所示:
const Users = () => {
const [toastOpen, setToastOpen] = useState(false)
// functions to handle toast closing
return (
<EditUser />
<Toast />
)
}
const EditUser = () => {
[user, setUser] = useState(null)
useEffect(() => {
const fetchedUser = await fetchUser()
setUser(fetchedUser)
}, [])
// this approach results in UserForm's username resetting when the toast closes
const Content = () => {
if (user) return <UserForm user={user} />
else return <div>Loading...</div>
}
return <Content />
// if I do this instead, everything's fine
return (
<div>
{
user ? <UserForm user={user} /> : <div>Loading...</div>
}
</div>
)
}
const UserForm = ({ user }) => {
const [username, setUsername] = useState(user.name)
return <input value={username}, onChange={e => setUsername(e.target.value)} />
}
在 Toast 仍然打开时查看用户窗体页面时,用户窗体状态会在 Toast 关闭时重置。
我已经发现问题出在Content
内部定义的组件EditUser
,但我不太清楚为什么这是一个问题。我很想了解一下 React 引擎盖下发生的事情,以及“快乐之路”中发生的事情