【问题标题】:Why does 'useState()' appear not to be working?为什么“useState()”似乎不起作用?
【发布时间】: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


【解决方案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)
     }
  }, []);

现在只需观察另一个 useEffect 块中状态 roles 的变化

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

【讨论】:

  • 试过了,结果相同 + 无限循环,因为它重新渲染了 Formik
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 2010-10-14
  • 2022-11-13
  • 2012-10-19
  • 2018-06-09
  • 1970-01-01
  • 2023-01-17
相关资源
最近更新 更多