The rewritten title is: Initial update of React state is not occurring
P粉401901266
P粉401901266 2023-09-08 22:29:43
0
2
442

I have an image upload component where the user can upload one or more images at a time. I always try to use useState() to update the state when the user uploads an image. But the status was not updated immediately. How can I update the following code to make it work properly.

import React from 'react';
import './style.css';
import React, { useState } from 'react';

export default function App() {
  const [file, setFile] = useState([]);

  const uploadImages = (event) => {
    console.log('NewFile=>', event.target.files);

    setFile([...file, ...event.target.files]);
    console.log('UpdatedFiles=>', file);
  };
  return (
    <div>
      <input
        multiple
        type="file"
        name="photo"
        id="photo"
        accept="image/*"
        capture="environment"
        onChange={(event) => uploadImages(event)}
      />
    </div>
  );
}

https://stackblitz.com/edit/react-ujcbjh?file=src/App.js

P粉401901266
P粉401901266

reply all(1)
P粉846294303

You should be careful whenever you use useState with non-primitive types.

These two pages from the React documentation will give you some instructions:

In short, react uses Object.is to determine whether state has changed between calls to setState. For objects and arrays, this may return true even if their contents change.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!