我需要动态生成一些对象属性。 (该对象是initialValues
组件的Formik
对象。)
当我尝试在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":""}
我在做什么错?是我的破坏吗?
答案 0 :(得分:1)
尝试使用useEffect
这样的东西。
这将在初始渲染时显示
const [roles, setRoles] = useState([]);
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)
}
}, []);
现在只需在另一个roles
块中观察状态useEffect
的变化
useEffect(() => {
const possibleRoles = {}
roles.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))
}, [roles]);