【发布时间】:2020-01-25 11:04:24
【问题描述】:
我有一些需要动态生成的对象属性。 (该对象是 initialValues 组件的 initialValues 对象。)
当我尝试在 useEffect() 调用中更新 formValues 时,它们似乎没有粘住。
useEffect(() => {
async function getRoles() {
let res
try {
res = await fetch(`http://localhost/roles?active=Yes`)
} catch (err) {
console.log('Err in getRoles', JSON.stringify(err))
}
const { rows } = await res.json()
console.log('rows: ' + JSON.stringify(rows))
setRoles(rows)
const possibleRoles = {}
rows.forEach((role, index) => {
const key = role.code.toLowerCase()
possibleRoles[key + '_reviewer'] = ''
})
console.log('formValues before: ' + JSON.stringify(formValues))
console.log('possibleRoles: ' + JSON.stringify(possibleRoles))
const newValues = { ...possibleRoles, ...formValues }
console.log('newValues: ' + JSON.stringify(newValues))
setFormValues({ ...newValues })
console.log('formValues after: ' + JSON.stringify(formValues))
}
getRoles()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []
)
// console results:
rows: [{"code":"aaa"},{"code":"bbb"},{"code":"ccc"}]
formValues before: {"formChoice":"","sectionChoices":[],"requestor":"dd","materials":""}
possibleRoles: {"aaa_reviewer":"","bbb_reviewer":"","ccc_reviewer":""}
newValues: {"aaa_reviewer":"","bbb_reviewer":"","ccc_reviewer":"","formChoice":"","sectionChoices":[],"requestor":"dd","materials":""}
formValues after: {"formChoice":"","sectionChoices":[],"requestor":"dd","materials":""}
我做错了什么?是我的解构吗?
【问题讨论】:
-
如果您的 Formik 状态已更新但未出现在浏览器中,请尝试在 formik 表单上使用
enableReinitialize道具。 -
您会看到之前的状态,因为
setState是异步的。 reactjs.org/docs/… -
当你想在useEffect中使用props时,你必须设置依赖,所以你应该把initialValues放在[]
-
如果我将 initialValues 放入 [],我会得到一个可爱的无限循环。
-
我曾假设 setState 上的
await会避免异步性质。
标签: reactjs ecmascript-6 react-hooks