React模态框重渲染输入值残留,状态更新正常问题排查
问题描述
表格每行带有“编辑”按钮,点击后会打开模态框编辑对应行的数据,输入字段通过onChange监听更新组件state。保存数据并关闭模态框后,再点击其他行的“编辑”按钮,模态框的输入框会残留之前修改过的字段值。
已确认props传递正确、state设置无问题,查看元素和state时显示的值是正确的,但输入框仍会遗留旧值。希望每次打开新行的模态框时,输入框能从传入的props中加载对应数据。
代码背景
- 将行数据作为props传递给模态框组件
- 模态框中使用
useEffect监听props的更新(切换不同行编辑时触发)
相关代码片段
父组件传递props到模态框
<EditConnectionModal connection={connection} setConnection={setConnection} initials={initials} getConnections={getConnections} />
模态框中的输入框代码
<header class="form-floating"> <input class="border rounded form-control form-control-lg text-light bg-dark-2" type="text" id="name" placeholder="Name" defaultValue={name} onChange={e => setName(e.target.value)}/> <label class="form-label text-start text-white-50" for="name">Full Name</label> </header>
模态框的状态与useEffect代码
const [name, setName] = React.useState("") const [email, setEmail] = React.useState("") const [company, setCompany] = React.useState("") const [website, setWebsite] = React.useState("")
React.useEffect(() => { setName(connection.name) setEmail(connection.email) setCompany(connection.company) setWebsite(connection.website) }, [user, isAuthenticated, connection])
解决方案
问题根源是你用了defaultValue绑定输入框,这个属性仅在组件首次渲染时生效,后续props更新不会同步到输入框的显示值。
把输入框的defaultValue替换成value,让输入框完全受控于组件state:
<input class="border rounded form-control form-control-lg text-light bg-dark-2" type="text" id="name" placeholder="Name" value={name} onChange={e => setName(e.target.value)} />
修改后,每次切换编辑行触发connection props更新时,useEffect会同步更新state,输入框会自动加载最新的props数据,不会再残留旧值。
另外,useEffect的依赖数组里的user和isAuthenticated如果和模态框的数据初始化无关,可以移除,减少不必要的重渲染:
React.useEffect(() => { setName(connection.name) setEmail(connection.email) setCompany(connection.company) setWebsite(connection.website) }, [connection])
内容的提问来源于stack exchange,提问作者rootcage
相关产品推荐
相关产品推荐

