【问题标题】:UseEffect runs while it should wait for await in other functionUseEffect 在其他函数中等待 await 时运行
【发布时间】:2021-09-27 19:57:48
【问题描述】:

我在使用 useEffect 和 async-await 函数时遇到问题,我不知道如何解释。让我试试:我有两个组件,父母和孩子,父母向孩子发送一些道具,包括修改某些状态的函数和状态。子进程在 useEffect 挂钩中使用此道具生成新状态,并使用 async-await 函数中的函数将状态修改回父进程中。孩子在异步函数内的 for 循环中使用此函数,但是,useEffect 继续运行并且不允许我修改父级中的所有状态。这是一个非常简化的代码,我希望足够了:

父函数

const createEntry = async(entry) => {
        const dummyEntries = clone(entries);
        console.log('Entradas:');
        console.log(dummyEntries);
        dummyEntries.push(entry);    
        setEntries(dummyEntries)    
        return json.id;
    }

它将条目和 createEntry 发送给孩子

子函数

useEffect(()=>{
//create some states, called entries, with props.entries
},[props.entries])

const Save = async () => {
    if (Object.values(error).some((e) => e.value === true)) {
      setModal(true);
    } else if (props.accion === 'crear') {
      for (const item of entries){
        await props.createEntry(item) 
      }
      history.push(`/path/`);
    } else if (props.accion === 'editar') {
      for (const item of entries){
        if (!item.id) {
          console.log(item)
          await props.createEntry(item)
        }
      }
      history.push(`/path`);
    }
  };

只有子组件的条目中的最后一个词保存在父组件的条目中

【问题讨论】:

  • 调用props.createEntry一次将调用setEntries,这将使useEffect函数再次运行,因为props.entries已更改。
  • 只保存最后一项,因为父组件和子组件对执行useEffect 钩子时生效的状态有一个闭包。我建议你先在状态中创建一个你想要保存的对象,然后循环之后,调用状态设置器函数。
  • 在子节点中,我应该将包含所有条目的对象发送给父节点,然后将其全部保存在父节点中?
  • 是的。不要在子组件的循环内调用从父传递的状态设置器函数。
  • 完美!它现在可以工作了 :) 所以,对于未来的编码,useEffect 并不关心异步等待,对吧?

标签: javascript reactjs async-await use-effect


【解决方案1】:

好的,谢谢评论者!这是工作代码:

父函数

const createEntry = async(new_entries) => {
   const dummyEntries = clone(new_entries);
   for (const entry of new_entries){
            dummyEntries=[...dummyEntries,json]
    }  

    setEntries(dummyEntries)   
    }

子函数

useEffect(()=>{
//create some states, called entries, with props.entries
},[props.entries])

const Save = async () => {
    if (Object.values(error).some((e) => e.value === true)) {
      setModal(true);
    } else if (props.accion === 'crear') {
      await props.createEntry(entries) 
      history.push(`/path/`);
    } else if (props.accion === 'editar') {
      await props.createEntry(entries)
      history.push(`/path`);
    }
  };

我使用 async-await 是因为中间有一些获取。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多