猿问

我在 React 中映射已创建的数组时遇到问题,并且正在尝试传播它(但无济于事)

我在这里设置了一个系统,单击保存按钮抓取一个div并制作一个可用的图像文件。我知道这是有效的,因为我已经让它与单个图像一起工作。我现在已将其设置为与同一图像的多个图像一起使用,但我似乎无法让它映射任何内容。我一直在阅读有关传播的文章,我正在尝试这样做,但它仍然不适合我。我以前遇到过这种挣扎,如果有人能解释为什么这不起作用,我会很高兴。我正在使用反应钩子。我也知道状态正在更新,据我所知是正确的。我大约99%确定问题出在映射中。


import React, { useState } from "react";

import "./Favorites.css";

import htmlToImage from "html-to-image";

import FileBase64 from "react-file-base64";


function Favorites(props) {

  const [files, setfiles] = useState([]);


  const newspreadarray = [...files];

  const getimage = () => {

    var htmlToImage = require("html-to-image");


    var node = document.getElementById("mymodal153");


    htmlToImage

      .toPng(document.getElementById("mymodal153"), { quality: 0.01 })

      .then(function (dataUrl) {

        var img = new Image();

        img.src = dataUrl;

        console.log(dataUrl);

        let newarray = files;

        newarray.push(dataUrl);

        console.log(newarray);

        setfiles(newarray);

      })

      .catch(function (error) {

        console.error("oops, something went wrong!", error);

      });

  };


  return (

    <div>

      <span onClick={getimage} className="minize close">

        save &minus;

      </span>

      <div className="imageholder">

        <div id="mymodal153">

          <img src="https://i.imgur.com/LFXgB63.png" class="dinoimage" />

          <h1>Cool</h1>

          <p>hi this is some example text</p>

        </div>

        <div id="imageplacer"></div>

        {newspreadarray.map((post, index) => (

          //we can fiddle with sizes here :)

          <img src={post} key={index} />

        ))}

      </div>

    </div>

  );

}


export default Favorites;


噜噜哒
浏览 149回答 1
1回答

白衣染霜花

问题是你正在改变状态。.then(function (dataUrl) {&nbsp; &nbsp; var img = new Image();&nbsp; &nbsp; img.src = dataUrl;&nbsp; &nbsp; console.log(dataUrl);&nbsp; &nbsp; let newarray = files; // <-- reference to state&nbsp; &nbsp; newarray.push(dataUrl); // <-- mutation&nbsp; &nbsp; console.log(newarray); // <-- save same reference back to state&nbsp; &nbsp; setfiles(newarray);})或更简洁setfiles([...files, dataUrl]);您应该创建一个新的数组引用.then(function (dataUrl) {&nbsp; &nbsp; var img = new Image();&nbsp; &nbsp; img.src = dataUrl;&nbsp; &nbsp; console.log(dataUrl);&nbsp; &nbsp; const newarray = [...files]; // <-- spread existing state into new array&nbsp; &nbsp; newarray.push(dataUrl); // <-- append new element&nbsp; &nbsp; console.log(newarray);&nbsp; &nbsp; setfiles([...files, dataUrl]); // <-- save new reference to state&nbsp; })这也是一条非常无用的线const newspreadarray = [...files];您可以简单地{files.map((post, index) => (&nbsp; //we can fiddle with sizes here :)&nbsp; <img src={post} key={index} />))}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答