【问题标题】:Push Data Into Array in State Array In Reactjs在 Reactjs 中将数据推送到状态数组中的数组中
【发布时间】:2021-04-27 11:28:36
【问题描述】:

大家好,希望一切顺利

我有一个问题我正在通过 ReactJs在 Cloudinary 中上传多个图像

这是输入字段

         <input
          type="file"
         className="form-control"
         required
         onChange={(e) => setImages(e.target.files)}
          multiple
           />

OnChange 我将所有文件存储在下面给出的状态

const [images, setImages] = useState([]);

现在我循环状态上传每个文件Cloudinary提取每个图像的URL代码如下

for (const file of images) {
  async function upload() {
    const formData = new FormData();
    formData.append("file", file);
    formData.append("upload_preset", "DummyPreset"); // Replace the preset name with your own
    formData.append("api_key", "0300545648961"); // Replace API key with your own Cloudinary key

    // Make an AJAX upload request using Axios (replace Cloudinary URL below with your own)
    await axios
      .post(
        "https://api.cloudinary.com/v1_1/Dummycloud/image/upload",
        formData,
        {
          headers: { "X-Requested-With": "XMLHttpRequest" },
        }
      )
      .then((response) => {
        const data = response.data;
        const fileURL = data.secure_url; // You should store this URL for future references in your app
        console.log(fileURL);
     
      });
  }

  upload();
}

在这里,我可以将每个链接提取为 fileURL 并对其进行控制

console.log(fileURL);

要查看输出请点击链接,它会将您重定向到图像Outputimage

如您所见,现在所有 URL 都已提取,我想将所有提取的 URL 推送到一个数组中,并希望将它们发送到 Express 服务器,然后我将它们存储到数据库中

请告诉我如何将所有 URL 存储到状态数组中,只要提取的任何 URL 都会存储到该数组中

【问题讨论】:

  • 使用状态钩子const [images, setImages] = React.useState([]),然后用setImages([...images, fileURL])reactjs.org/docs/hooks-state.html更新你的状态
  • 不工作的兄弟
  • 向我们展示您的尝试,以便我们进一步帮助您。
  • await axios .post( "https://api.cloudinary.com/v1_1/Dummycloud/image/upload", formData, { headers: { "X-Requested-With": "XMLHttpRequest" }, } ) .then((response) =&gt; { const data = response.data; const fileURL = data.secure_url; setImages([...images, fileURL]); }); } upload(); } 问题是状态没有实时更新
  • 不,那行不通。我发布了一个答案。

标签: javascript arrays reactjs mern use-state


【解决方案1】:

这里是解决方案

感谢您的贡献

 var ImagesUrlArray = [];
for (const file of image) {

  async function upload() {
     const formData = new FormData();
formData.append("file", file);
formData.append("upload_preset", "DummyPreset"); // Replace the preset name with your own
formData.append("api_key", "0300545648961"); // Replace API key with your own Cloudinary key

// Make an AJAX upload request using Axios (replace Cloudinary URL below with your own)
await axios
  .post(
    "https://api.cloudinary.com/v1_1/Dummycloud/image/upload",
    formData,
    {
      headers: { "X-Requested-With": "XMLHttpRequest" },
    }
  ).then((response) => {
        const data = response.data;
        var fileURL = data.secure_url; // You should store this URL for future references in your app
        
        ImagesUrlArray = [...ImagesUrlArray];

        ImagesUrlArray.push(fileURL);

        if (ImagesUrlArray.length === image.length) {
          
          const res = axios
            .post("http://localhost:5000/register", {
              fullname: Data.fullname,
              email: Data.email,
              pass: Data.pass,
              cpass: Data.cpass,
              phone: Data.phone,
              imagee: ImagesUrlArray,
            })
            .then((response) => response);

          setdataa(res);
        }
      });
  }

  upload();
}

【讨论】:

    【解决方案2】:
    // this function returns a Promise
    const uploadFile = (file) => {
      const formData = new FormData();
      formData.append(stuff);
      return axios.post('some/path', formData).then(response => response.data.secure_url);
    };
    
    Promise.all(images.map(uploadFile)).then(fileURLs => storeFileURLs(fileURLs))
    

    【讨论】:

    • @TalhaZubairMayo 告诉我你是如何将我的代码 sn-p 集成到你的组件中的,我也许可以帮助你。
    猜你喜欢
    • 1970-01-01
    • 2016-03-26
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2016-06-19
    • 2015-03-31
    • 1970-01-01
    • 2018-07-07
    相关资源
    最近更新 更多