当对象数组更改时 useState 不会导致重新渲染 *hooks*

时间:2021-04-21 16:31:08

标签: reactjs react-hooks

我有一个对象,它有许多键,每个键都有一个对象数组。每个对象都包含一个图像文件,我需要显示该文件以预览用户刚刚上传的图像。但是显示的是上次上传的图片(不是刚刚上传的图片)

显然 useState 不会立即导致重新渲染,除非它看到数组或对象发生变化 How do I update states onchange in an array of object in React Hooks

我遵循了上述(以及来自 StackOverflow 的一些类似建议)并在键处制作了对象的副本和数组的副本,但它仍然不起作用

知道为什么吗?

const Form = props => {
let [images, setImages] = useState({
    bannerPicture: [],
    projectPictures: [],
    projectsPictures: [],
    thumbnailPictures: []
})
const showTempImage = (file, tempFileObj, key) => {
    const imagesCopy = {...images}
    // add this image to the end of the array at the given key
    imagesCopy[key] = [...imagesCopy[key], tempFileObj]
    setImages({...imagesCopy})
....

}

我只希望图片在用户上传后立即显示

1 个答案:

答案 0 :(得分:0)

通过您的 async 函数进行操作。

我假设您只会在上传完成后显示图片。

const mockUploadApi = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve("uploadedImage");
    },1000);
  });
};


const App = () => {

  const [state,setState] = React.useState({
    status: "IDLE",
    image: ""
  });
  
  const uploadImage = () => {
    setState((prevState) => ({
      ...prevState,
      status: "UPLOADING"
    }));

    // THIS SHOULD USE await BUT THE SNIPPET DOES NOT ALLOW IT
    // SO I'M USING .then()
    
    mockUploadApi().then((uploadedImage) => {
      setState({
        status: "IDLE",
        image: uploadedImage
      });
    });
  };

  return(
    <div>
      <div>
        status: {state.status}
      </div>
      <div>
        image: {state.image || "no image"}
      </div>
      <div>
        <button onClick={uploadImage}>
          Upload
        </button>
      </div>
    </div>
  );
};

ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>