首页 > 解决方案 > 为什么即使在定义之后也会出现 setstate 错误?

问题描述

在我的代码中,我试图从 nodejs 中获取价值并试图在反应中展示。我的图像格式是base64。然后我尝试设置状态,但它给了我名为 setstate 的错误未定义。我的设置状态是图像。谁能告诉错误是什么?文件上传.js:

const getImage = () => {
    console.log('getImage');
    axios.get(`http://localhost:3001/api/showallimages`).then((result) => {
        this.setState({image: result});
        console.log(result);
    });
}
getImage();

  return (
    <div className="App">
      <input
        type="file"
        onChange={(e) => {
          uploadImage(e);
        }}
      />
      <button onClick={saveImage}>Save</button>
      <br/>
</div>
  );
}

export default File;

服务器.js:

app.get('/api/showallimages',(req,res)=>{
    mysqlConnection.query('SELECT * FROM imagetb',(err,rows,fields)=>{
    if(!err)
    res.send(rows);
    else
        console.log(err);
})
});

app.listen(3001, () => {
  console.log("Server Running On 3000");
});

编辑,这是未添加的代码,它是 Fileupload.js 的一部分:

import React, { useState } from "react";
import "./App.css";
import axios from 'axios';

function File() {
  // const [baseImage, setBaseImage] = useState("");
const [image] = useState("");
  const uploadImage = async (e) => {
    const file = e.target.files[0];
    const base64 = await convertBase64(file);
    window.bs64=base64;
    saveImage();
    //setBaseImage(base64);
  };

  const convertBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);

      fileReader.onload = () => {
        resolve(fileReader.result);
      };

      fileReader.onerror = (error) => {
        reject(error);
      };
    });
  };

const saveImage = () => {
  axios.post("http://localhost:3001/api/image",{
    imgName: window.bs64,
  });
};

const getImage = () => {
    console.log('getImage');
    axios.get(`http://localhost:3001/api/showallimages`).then((result) => {
        this.setState({image: result});
        console.log(result);
    });
}
getImage();

  return (
    <div className="App">
      <input
        type="file"
        onChange={(e) => {
          uploadImage(e);
        }}
      />
      <button onClick={saveImage}>Save</button>
      <br/>
</div>
  );
}

export default File;

标签: javascriptnode.jsreactjs

解决方案


对于基于类的方法

import React from 'react';
        import axios from 'axios'
        
        class File {
        
           constructor(){
             this.state = {
                image: '',
                text: ''
             }
            this.getImage = this.getImage.bind(this) // Not needed if you use arrow function
           }
        
          componentDidMount(){
             this.getImage();
          }
        
          getImage(){
            axios.get(`http://localhost:3001/api/showallimages`).then((result) => {
                console.log(result);
                this.setState({image: result});
            });
           }

    
    render(){
        return (
            <div className="App">
                <button>Save</button>
            </div>
          );
      }
            
    }
            
     export default File;

和你的功能方式

import React, { useState, useEffect } from "react";
import "./App.css";
import axios from 'axios';

function File() {
 
const [state, setState] = useState("");

 const getImage = () => {
        console.log('getImage');
        axios.get(`http://localhost:3001/api/showallimages`).then((result) => {
            setState({image: result});  //setState defined above as updater
            console.log(result);
        });
    }
 
useEffect(()=>{
   getImage();
},[])




  return (
    <div className="App">
      <button>Save</button>
    </div>
  );
}

export default File

推荐阅读