【问题标题】:Why setstate error is coming even after defining it? [closed]为什么即使在定义之后也会出现 setstate 错误? [关闭]
【发布时间】:2021-06-29 21:42:18
【问题描述】:

在我的代码中,我试图从 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;

Server.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;

【问题讨论】:

  • 您可能正在使用函数组件。 this.setState 仅适用于类组件。请参阅 hooks 上的 React 文档,特别是 useState 钩子。
  • 那么我怎么能把它放在课堂上,因为我有其他不在代码中的对象?
  • 不要将代码块放在 cmets 中,edit 你的问题是为了添加更多上下文。
  • 我真的认为对您最有帮助的事情是阅读链接的文档并尝试理解它。看起来你的问题在这里const [image] = useState("");。您没有获得更新程序功能。可以像const [image, setImage] = useState(""); 一样简单,然后使用setImage 而不是this.setState
  • 查看 useEffect 钩子,将空数组作为依赖项。

标签: javascript node.js reactjs


【解决方案1】:

对于基于类的方法

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

【讨论】:

    【解决方案2】:

    setState 仅适用于类组件,其中功能组件使用useState 挂钩。使用 useState 或将您的组件作为类。

    import React from 'react'
    
    export default class App extends React.Component {
       
       constructor(props){
           super(props)
           this.state = {
               image: ''
           }
       }
    
       getImage = () => {
    axios.get(`http://localhost:3001/api/showallimages`).then((result) => {
               this.setState({image: result});
           });
       }
       
       uploadImage = (e) => {
        //Your code
       }
       
       saveImage = (e) => {
        //Your code
       }
       
       render() {
          return (
            <div className="App">
              <input
                type="file"
                onChange={(e) => {
                  this.uploadImage(e);
                }}
              />
              <button onClick={this.saveImage}>Save</button>
              <br/>
            </div>
          )
       }
       
       componentDidMount(){
          this.getImage();
       }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

    【讨论】:

      【解决方案3】:

      所以您似乎发布了不完整的代码,但如果问题是为什么“this.setState”未定义,那是因为您混淆了功能组件和基于类的组件。

      这是一个功能组件,如果您希望组件具有任何本地状态,您可以在其中使用 useState。 useState 返回一个 getter 和一个 setter 的元组。在这种情况下,您只能通过 setter - setGreeting 来操作状态。

      const Greeter = (props) => {
          const [greeting, setGreeting] = useState("Hello")
      
          const updateGreeting = () => {
              setGreeting("Bye");
          }
      
          return (
              <div>
                  <div>{ greeting }</div>
                  <button click={updateGreeting}></button>
              </div>
          )
      }
      

      这是一个基于类的组件。基于类的组件确实有 this 引用,因为它们是常规的 JavaScript 类。它们确实有一个属性状态和一个对应的 setter-method setState。

      class Greeter extends React.Component {
          constructor(props) {
              super(props);
              this.state = { greeting: "Hello" };
          }
      
          updateGreeting(){
              this.setState({ greeting: "Bye" };
          }
          
      
          render() {
             return (
                 <div>
                     <div>{ this.state.greeting }</div>
                     <button click={updateGreeting}>Update greeting</button>
                 </div>
             )
          }
      }
      

      您可以混合和匹配基于类的组件和功能组件。我发现功能组件的读写更加优雅。查看 React Conf 的介绍性演讲,以更轻松地了解 hooks:https://www.youtube.com/watch?v=dpw9EHDh2bM

      【讨论】:

        【解决方案4】:

        const [image] = useState(""); 变为 const [image, setImage] = useState(""); this.setState({image: result}); 变为 setImage(result)

        切换这个:

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

        到这里(别忘了跟useState一样导入useEffect)

        useEffect(()=>{
        axios.get(`http://localhost:3001/api/showallimages`).then((result) => {
                console.log(result);
                setImage(result)
            });
        },[])
        

        我强烈建议您研究一下 useEffect 挂钩的工作原理。这里的空数组只是意味着它将在组件的第一次渲染时运行。

        【讨论】:

        • 这段代码几乎是正确的,但我想在不点击按钮的情况下提出请求
        • 就像body开始时一样
        • 我之前也这样做过,但它不发送自动请求
        • 如果此代码解决了您在原始问题中的错误,则问题已解决。任何进一步的事情都超出了问题的范围。
        • 我还在 cmets 中询问了如何打印这个所以至少告诉我这样我的问题就可以解决了
        猜你喜欢
        • 2012-05-17
        • 1970-01-01
        • 2019-07-29
        • 2015-03-08
        • 2020-02-27
        • 1970-01-01
        • 2021-09-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多