0

我有一些需要动态生成的对象属性。(对象是组件的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":""}

我究竟做错了什么?是我的解构吗?

4

1 回答 1

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]);
于 2020-01-25T11:31:39.563 回答