我正在使用React钩子在一个项目中工作。但是,我尝试使用不带useState钩子的变量来处理变量。问题是,当我运行包含数组操作的函数时,似乎没有考虑到这一点,因此跳过了这一步。我以这种方式进行了更改(您将在代码中很快看到),因为我使用的是一个连续添加更多值的数组,所以我认为这样做更容易。
您能帮我解决这个问题或向我解释为什么这不起作用吗?
这里是代码:
let platosRegVent:any = []; // This is how I'm declaring my array
const agregarPlato = async () => {
if(validarCamposPlato()){
try{
let valorParcial = 0;
let platoExist = await encontrarPlato(config, rvPlato);
if(platoExist === true){
setAgregadoMin(true);
platoCodigo = await obtenerCodigoPlato(config, rvPlato);
platosRegVent.push({codigoPlato: platoCodigo, cantidad: rvCantidad}); // Here is where I'm adding more objects to my array.
let costoPlato = await obtenerValorPlato(config, rvPlato);
valorParcial = valorTotal;
setValorTotal(valorParcial += (costoPlato * parseInt(rvCantidad)));
setRvPlato('');
setRvCantidad('');
}
else{
toast.error('El plato ingresado no se ha encontrado.');
setRvPlato('');
}
}
catch(error){
toast.error('Un error inesperado ha ocurrido, por favor intente mas tarde.');
props.handleSubmit();
}
}
}
const finalizarRegVent = async () => {
console.log(agregadoMin);
if(validarCampos()){
try{
if(rvPlato !== '' || rvCantidad !== ''){
await agregarPlato();
}
if(agregadoMin === true){
rvCodigo = await crearRegistroVenta(config, valorTotal, fechaActual, regVentMesa);
platosRegVent.forEach( (plato : any) => { //Here is the operation of the array. It seems that this step is skipped.
crearRegVentPlato(config, rvCodigo, plato.codigoPlato, plato.cantidad);
});
setValorFinal(false);
}
else{
toast.error('Debe ingresar por lo menos un plato para completar el registro.');
}
}
catch(error){
toast.error('Un error inesperado ha ocurrido, por favor intente mas tarde.');
props.handleSubmit();
}
}
}
您应该改用useState()和useCallback()挂钩。因为React的机制仅在检测到状态变化时才更新。如果创建静态变量,则react无法更新其值。或者,useRef()为您提供解决方案。