0

我正在从事一个个人项目,以了解更多关于反应钩子工作方式的信息。最近我发布了一个问题,我在 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>
);}

感谢您的帮助

4

2 回答 2

1

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

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

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

useEffect(()=> {
  doSomethingWithFooOrBar();
}, [foo, bar]);
于 2020-05-20T03:12:27.057 回答
1

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

像这样:

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]
) 
于 2020-05-20T03:32:14.643 回答