setState 没有立即更新
setState isn't updating immediately
我正在使用 React 应用程序,我正在尝试更新状态,但它不会立即更新。我在互联网上查找并找到了它,但问题是,所有这些人都在使用 类 组件,而我正在使用功能组件。他们在谈论 setState 函数中的回调,但我在我的代码中试过了,但没有成功!!
这是我的代码:
async function handleSelectImage(event: ChangeEvent <HTMLInputElement>) {
if (!event.target.files) {
return;
}
const selectedImages = Array.from(event.target.files);
selectedImages.map((image) => {
if (!(image.type === 'image/png' || image.type === 'image/jpg' || image.type === 'image/jpeg')) {
const imageIndex = selectedImages.indexOf(image);
selectedImages.splice(imageIndex, 1);
alert('Só são aceitos arquivos jpeg, jpg e png.');
}
});
try {
setImages(images.concat(selectedImages));
} catch (err) {
console.error(err);
}
console.log(images);
希望你能帮帮我!!!!
谢谢!!! :)
无法在 React 的功能组件中读取状态,因为它是一个异步操作。
所以,不是你的状态没有更新,而是你的 console.log(images) 函数在更新状态 returns 的异步函数之前被调用和读取。
好的...那该怎么办呢?
两种选择:
1。将状态传递到另一个组件并在那里读取它。
这是首选,imo,因为您可以将有状态组件与“哑”组件分开。
所以在上面的组件中,您可以将 images
作为 prop 传递给子组件:
在 ImageDisplay 内部,从 props 获取图像状态。
2。等待异步函数在您的组件内更新。
如果你真的想在你的功能组件中读取状态,你必须等待异步函数到 return。为此,我认为最简单的方法是设置一个“等待”状态,就像这样。
const [isLoading, setLoading] = useState(true);
/// rest of your call and your async function
///try block:
try {
setImages(images.concat(selectedImages));
setLoading(false);
} catch (err) {
console.error(err);
}
if(setLoading) {
console.log("The images haven't loaded yet");
} else {
console.log(images)
}
基本上,您为组件提供了等待图像状态更改的条件。当该条件不再为真时,图像将准备好显示。 (您也可以在前端渲染数据,而不仅仅是控制台!)
祝你好运。
我正在使用 React 应用程序,我正在尝试更新状态,但它不会立即更新。我在互联网上查找并找到了它,但问题是,所有这些人都在使用 类 组件,而我正在使用功能组件。他们在谈论 setState 函数中的回调,但我在我的代码中试过了,但没有成功!!
这是我的代码:
async function handleSelectImage(event: ChangeEvent <HTMLInputElement>) {
if (!event.target.files) {
return;
}
const selectedImages = Array.from(event.target.files);
selectedImages.map((image) => {
if (!(image.type === 'image/png' || image.type === 'image/jpg' || image.type === 'image/jpeg')) {
const imageIndex = selectedImages.indexOf(image);
selectedImages.splice(imageIndex, 1);
alert('Só são aceitos arquivos jpeg, jpg e png.');
}
});
try {
setImages(images.concat(selectedImages));
} catch (err) {
console.error(err);
}
console.log(images);
希望你能帮帮我!!!! 谢谢!!! :)
无法在 React 的功能组件中读取状态,因为它是一个异步操作。
所以,不是你的状态没有更新,而是你的 console.log(images) 函数在更新状态 returns 的异步函数之前被调用和读取。
好的...那该怎么办呢?
两种选择: 1。将状态传递到另一个组件并在那里读取它。 这是首选,imo,因为您可以将有状态组件与“哑”组件分开。
所以在上面的组件中,您可以将 images
作为 prop 传递给子组件:
在 ImageDisplay 内部,从 props 获取图像状态。
2。等待异步函数在您的组件内更新。 如果你真的想在你的功能组件中读取状态,你必须等待异步函数到 return。为此,我认为最简单的方法是设置一个“等待”状态,就像这样。
const [isLoading, setLoading] = useState(true);
/// rest of your call and your async function
///try block:
try {
setImages(images.concat(selectedImages));
setLoading(false);
} catch (err) {
console.error(err);
}
if(setLoading) {
console.log("The images haven't loaded yet");
} else {
console.log(images)
}
基本上,您为组件提供了等待图像状态更改的条件。当该条件不再为真时,图像将准备好显示。 (您也可以在前端渲染数据,而不仅仅是控制台!)
祝你好运。