setState不会立即更新

时间:2020-11-07 02:48:57

标签: reactjs typescript file setstate react-functional-component

我正在使用反应应用程序,并且我正在尝试更新状态,并且它不会立即更新。我在互联网上寻找它,但发现的问题是,所有这些人都在使用类组件,而我在使用功能组件。他们正在谈论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);


希望您能帮助我!!!! 谢谢!!! :)

1 个答案:

答案 0 :(得分:0)

状态无法在React的功能组件中读取,因为它是异步操作。

因此,并不是状态ISN不会更新,而是在更新状态的异步函数返回之前调用并读取了console.log(images)函数。

好的...那该怎么办?

两个选项: 1。将状态传递到另一个组件中并在那里阅读。 首选imo,因为您可以将有状态组件与“哑”组件分开。

因此,在上面的组件中,您可以将images作为道具传递给子组件:

在ImageDisplay内,从道具中获取图像状态。

2。等待异步功能在组件内部更新。 如果您确实想读取功能组件内部的状态,则必须等待异步函数返回。为此,我认为最简单的方法是像这样设置“等待”状态。

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)
}

基本上,您为组件提供了条件,以等待图像状态更改。当该条件不再成立时,将可以显示图像。 (您也可以在前端上渲染数据,而不仅仅是控制台!)

祝你好运。

相关问题