簡體   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