为什么“ useState()”似乎不起作用?

时间:2020-01-25 11:04:24

标签: reactjs ecmascript-6 react-hooks

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

我在做什么错?是我的破坏吗?

1 个答案:

答案 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]);