Javascript 如果我';我已经在用useEffeck钩子了?
我在一个个人项目中工作,以了解更多关于react hooks工作方式的信息。 最近我发布了一个问题,我在axios调用中使用了一个变量,当我试图更新它(setVariable)时,它不起作用。答案是,我知道useState会进行异步调用,所以我的变量不会更新,所以我可以使用useEffect来解决这个问题 但现在我正在做另一个axios调用,我已经在该组件中使用了我的useEffect钩子,所以我认为它不能被使用两次。你能解释一下在这种情况下我能做什么吗 以下是我正在使用的组件:Javascript 如果我';我已经在用useEffeck钩子了?,javascript,reactjs,typescript,react-hooks,Javascript,Reactjs,Typescript,React Hooks,我在一个个人项目中工作,以了解更多关于react hooks工作方式的信息。 最近我发布了一个问题,我在axios调用中使用了一个变量,当我试图更新它(setVariable)时,它不起作用。答案是,我知道useState会进行异步调用,所以我的变量不会更新,所以我可以使用useEffect来解决这个问题 但现在我正在做另一个axios调用,我已经在该组件中使用了我的useEffect钩子,所以我认为它不能被使用两次。你能解释一下在这种情况下我能做什么吗 以下是我正在使用的组件: type mo
type modalBodyFormProps = {
handleSubmit: any,
objectS: any
}
const ModalBodyUpdatePreparacion:React.FC=(props:modalBodyFormProps)=>{
const[stockPreparaciones,setStockPreparaciones]=useState([]);
const[ingspreadaciones,setingspreadaciones]=useState([]);
useffect(()=>{
getPreparaciones();
GetingRedientPrep();
},[stockPreparaciones.长度];
常量getPreparaciones=()=>{
console.log(props.objectS);
axios.get()https://inventario-services.herokuapp.com/invservice/stock/getone/?codigo=“+props.objectS)
。然后(结果=>{
控制台日志(结果);
setStockPreparaciones(result.data.preparaciones);//在这里我需要使用useEffect挂钩,以便更新此值
控制台日志(stockPreparaciones);
}).catch(console.log);
}
常量GetingRedientPrep=()=>{
stockPreparaciones.map(st=>{
axios.get()https://inventario-services.herokuapp.com/invservice/stock/getone/?codigo=“+st.codigo_preparacion)
。然后(结果=>{
控制台日志(结果);
SetingsPrepareAciones([…ingsPrepareAciones,result.data]);//我想更新此值,但它显示为空。
控制台日志(控制台);
});
});
}
返回(
);}
感谢您的帮助您可以随时使用挂钩。您必须注意的唯一一件事是依赖项数组,并小心组合。你甚至可以这样做
useEffect(()=> {
doSomethingWithFoo();
}, [foo]);
useEffect(()=> {
doSomethingWithBar();
}, [bar]);
useEffect(()=> {
doSomethingWithFooOrBar();
}, [foo, bar]);
你可以在你想要的时候使用钩子。您必须注意的唯一一件事是依赖项数组,并小心组合。你甚至可以这样做
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]
)
根据需要分开使用。此外,利用模式 像这样:
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]
)
useffect
将依赖项作为第二个参数<代码>[stockPreparaciones.length]将侦听1个变量。请尝试[StockPrepareAciones,ingsPrepareAciones]
而不是useEffect
将依赖项作为第二个参数<代码>[stockPreparaciones.length]将侦听1个变量。请改为尝试[StockPrepareAciones,ingsPrepareAciones]