繁体   English   中英

如果我已经在使用 useEfeck 挂钩,如何更新我的 useState 变量?

[英]How can update my useState variable if I'm already using useEffeck hook?

我正在从事一个个人项目,以了解更多关于反应钩子工作方式的信息。 最近我发布了一个问题,我在 axios 调用中使用了一个变量,当我尝试更新它(setVariable)时,它没有用。 我了解到 useState 进行异步调用的答案,所以我的变量没有更新,所以我可以使用 useEffect 来解决这个问题。

但是现在我正在做另一个 axios 调用,并且我已经在该组件中使用了我的 useEffect 钩子,所以我认为它不能被使用两次。 你能解释一下在这些情况下我能做什么吗?

这是我正在使用的组件:

type modalBodyFormProps = {
handleSubmit: any,
objectS: any

}

const ModalBodyUpdatePreparacion: React.FC = (props: modalBodyFormProps) => {

const[stockPreparaciones, setStockPreparaciones] = useState<any[]>([]);
const[ingsPreparaciones, setIngsPreparaciones] = useState<any[]>([]);

useEffect(() => {
    getPreparaciones();
    getIngredientePrep();
},[stockPreparaciones.length]);

const getPreparaciones = () => {
    console.log(props.objectS);
    axios.get('https://inventario-services.herokuapp.com/invservice/stock/getone/?codigo=' + props.objectS)
    .then(result => {
        console.log(result);
        setStockPreparaciones(result.data.preparaciones); //Here is where I need to use useEffect hook so this value can be updated
        console.log(stockPreparaciones);
    }).catch(console.log); 
}

const getIngredientePrep = () => {
    stockPreparaciones.map(st => {
        axios.get('https://inventario-services.herokuapp.com/invservice/stock/getone/?codigo=' + st.codigo_preparacion)
        .then(result => {
            console.log(result);
            setIngsPreparaciones([...ingsPreparaciones, result.data]); //I want to update this value, however it appears as empty.
            console.log(ingsPreparaciones);
        });
    });
}

return(
    <div>

    </div>
);}

谢谢您的帮助

您可以使用钩子 useEffect 您想要的时间。 您唯一必须注意的是依赖数组,并注意组合。 你甚至可以这样做。

useEffect(()=> {
  doSomethingWithFoo();
}, [foo]);

useEffect(()=> {
  doSomethingWithBar();
}, [bar]);

useEffect(()=> {
  doSomethingWithFooOrBar();
}, [foo, bar]);

根据需要分开效果。 另外,使用异步等待模式。

像这样:

const { objectS } = props;

useEffect(
  async () => {
    const result = await axios.get(`heroku_url/?codigo=${objectS}`);
    setStockPreparaciones(result.data.preparaciones);    
  }
  , [objectS]
);

// watcher for state updates
useEffect(
  () => {
    console.log(stockPreparaciones)
  }
  , [stockPreparaciones]
) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM