【问题标题】:React Hooks: updating state using useState does not update the state immediately [duplicate]React Hooks:使用useState更新状态不会立即更新状态[重复]
【发布时间】:2020-05-12 11:50:08
【问题描述】:

我有一个包含多个字段的表单,其中一个字段包含一个对象数组。

它几乎添加了一个对象,其中包含来自主窗体的子窗体的值。

const addNode = () => {
    let p_form = pForm
    let ha = [vForm, yForm, hForm]
    let info = [....]
    setCurrentNodeForm(
        {
            ...currentNodeForm,
            p: p_form,
            ha: ha,
            info: info,
        }
    )
    // inserts this form to a state called `addedNodes`
    let currArr = [...addedNodes]
    currArr.push(currentNodeForm)
    setAddedNodes(currArr)
    intializeForms()
}

这是我用作Add 按钮的onClick 函数的函数。

这会将一个新对象添加到名为addedNodes 的状态中,该状态是一个对象数组。

然后当我提交我的主表单时,我将下面的函数用作onClick 函数

const submitMainForm = () => {
    let credentials = [...]
    let nodes = [...addedNodes]
    setMainForm(
        {
            ...currentMainForm,
            credentials: credentials,
            nodes: nodes,
        }
    )

    let body = {
        name: .... // something
        objects: currentMainForm,
    }

    intializeForms()

    let options = {
        headers: header,
        method: 'post',
        mode: 'cors',
        body: JSON.stringify(body),
    }

    console.log('options.body', options.body)

    return new Promise((resolve, reject) => {
        fetch(endpoint, options)
            .then(res => res.json())
            .then(resText => {
                console.log('resText', resText)
            })
    }).catch(err => {
        console.log(err)
    })
}

它的作用是,它使用我使用上面的addNode 函数更新的当前addedNodes 对象数组更新状态currentMainForm。但是,当我如上图console.logoptions.body 时,body 中的objects 字段为空。因此,当我发送 POST 请求时,body 缺少其关键部分。

当我在函数之外console.log 时,它会出现。

我想知道如何保证在函数内部正确更新状态。

提前致谢。

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    React hook 中执行副作用。如果是功能组件,则在useEffect钩子中添加api调用。

    setMainForm 是一个异步函数,因为它是 async 的性质,所以您在正文中没有数据。

    你可以做什么,更新提交函数中的状态,并使用useEffect钩子监听currentMainForm状态的变化并提交你的数据。

    示例

    useEffect( () => {
      fetchData();
    }, [currentMainForm]);
    
    const submitMainForm = () => {
      let credentials = [...]
      let nodes = [...addedNodes]
      setMainForm( prevState => {
        return  {
          ...currentMainForm,
          credentials: credentials,
          nodes: nodes,
        }
      });
    }
    
    function fetchData() {
      let body = {
        name: '....', // something
        objects: currentMainForm,
      }
    
      intializeForms()
    
      let options = {
          headers: header,
          method: 'post',
          mode: 'cors',
          body: JSON.stringify(body),
      }
    
      console.log('options.body', options.body)
    
      return new Promise((resolve, reject) => {
          fetch(endpoint, options)
              .then(res => res.json())
              .then(resText => {
                  console.log('resText', resText)
              })
      }).catch(err => {
          console.log(err)
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 2019-06-26
      • 2021-09-09
      • 2021-12-25
      • 1970-01-01
      • 2018-08-12
      • 2021-12-17
      相关资源
      最近更新 更多