简体   繁体   English

React Hooks useState 数组渲染两次

[英]React Hooks useState array rendering two times

I need to upload images to my useState by using a function and after that I want to render this images the problem is I do not know how to render my returned array here is the code Code:我需要使用 function 将图像上传到我的 useState 之后我想渲染这些图像问题是我不知道如何渲染我返回的数组这里是代码代码:

  const [logoImg, logoUpdater] = useState();
  const [title, updateTitle] = useState();
  const [carouselImages, carouselImagesUpdater] = useState([]);
  useEffect(
    (e) => {
      if (carouselImages.length > 0) {
      }
    },
    [carouselImages]
  );

  const carouselUploader = (file) => {
    var addedFile = file.target.files[0];
    carouselImagesUpdater((carouselImages) => [...carouselImages, addedFile]);
  };
  const titleFunction = () => {
    Preview(title);
  };
  return (
    <div>

      <div>
        <p>Upload Carousel images</p>
        <input
          type="file"
          accept="image/*"
          multiple
          onChange={(e) => carouselUploader(e)}
        ></input>
        {carouselImages.map((img) => (
          <img src={img} key="s"></img>
        ))}

Re rendering multiple times is not what shows you broken images for your selected files.多次重新渲染并不是向您显示所选文件的损坏图像。 Here is an example of how you can set the file:以下是如何设置文件的示例:

 const App = () => { const [ carouselImages, carouselImagesUpdater, ] = React.useState([]); const carouselUploader = (e) => { const reader = new FileReader(); reader.addEventListener('load', (event) => { carouselImagesUpdater((carouselImages) => [...carouselImages, event.target.result, ]); }); reader.readAsDataURL(e.target.files[0]); }; return ( <div> <p>Upload Carousel images</p> <input type="file" accept="image/*" multiple onChange={(e) => carouselUploader(e)} ></input> {carouselImages.map((img, index) => ( <img key={index} src={img}></img> ))} </div> ); }; ReactDOM.render(<App />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script> <div id="root"></div>

Here is some documentation on how to read files.是一些有关如何读取文件的文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM