React 在函数调用后刷新组件

React refreshes component after function call

我正在尝试创建一个投资组合,用于显示我的所有 ML 项目,这些项目可以通过简单的 API 调用显示,因此我决定创建一个 WebApp。我在前端使用 React,在后端使用 Django。目标是制作一个不需要刷新或更改页面的单一页面。

我几乎完成了所有工作,但是在测试第一个项目的 API 时,我注意到在 API 的函数调用之后,页面会刷新,但我无法刷新似乎弄清楚为什么会这样。

应用组件:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      menu: 1,
      file: null
    };
  }

  fileSelect = event =>{
    this.state.file = event.target.files[0];
  }

  update_menu_item(new_item){
    this.setState({menu: new_item});
  }

// HERE PROBLEM
  uploadSelfie(){
    const fd = new FormData();
    fd.append('image', this.state.file)
    axios
    .put("http://127.0.0.1:8000/api/obtainFaceEmotionPrediction", fd)
    .then((response) => {
      if (response.data){
        // window.alert(response.data.file);
        // Here even if I were to delete everything in this if statement, it would still refresh the page
        document.getElementById("article").innerHTML +=
              "<img src='../frontend/public/pictures_saved/face_emotion/" + response.data.file + "'/>";
      }
    })
    .catch((err) => console.log(err));
  }

  uploadMilitary(){
    // code not finalized yet. will be similar with uploadSelfie function but will handle multiple pictures
  }


  generate_segment(){
    let uiItems = [];

    if(this.state.menu === 1){
      uiItems.push(
        <article id="article">
          <h2 id="title">My ML Projects</h2>
          <div id="options">
            <ul>
              <li><button className="active" id="about" onClick={(e) => this.update_menu_item(1)}>About</button></li>
              <li><button id="face_emotion_detection" onClick={(e) => this.update_menu_item(2)}>Face Emotion Detection</button></li>
              <li><button id="military_detection" onClick={(e) => this.update_menu_item(3)}>Military Detection</button></li>
            </ul>
          </div>

          <p>The scope of this application is to showcase all of the ML projects that I have finished. The application features a WebApp where the frontend is designed in React and the backend in Django.</p>
          <p>Using REST API I'm able to make a call from the frontend to the backend. There, depending on the selected project, a pre-trained ML model will take your input and serve your request.</p>
          <p>If you want to check the source code for each of these projects and more, you can do so by using this <a href="https://github.com/LCCosmin?tab=repositories">link</a>.</p>
        </article>
      )
    }
    else if(this.state.menu === 2){
      uiItems.push(
          <article id="article">
            <h2 id="title">My ML Projects</h2>
            <div id="options">
              <ul>
                <li><button id="about" onClick={(e) => this.update_menu_item(1)}>About</button></li>
                <li><button className="active" id="face_emotion_detection" onClick={(e) => this.update_menu_item(2)}>Face Emotion Detection</button></li>
                <li><button id="military_detection" onClick={(e) => this.update_menu_item(3)}>Military Detection</button></li>
              </ul>
            </div>

            <p>The aim of this project is to detect both the face and the emotion of a person. Upload a selfie with you and see how the model works:</p>
            <input
              type="file"
              name="picture"
              id="picture"
              placeholder="Upload a Selfie"
              onChange={this.fileSelect}
            />
              <input
                type="button"
                value="Submit"
                onClick={(e) => this.uploadSelfie()}
              />
          </article>
        )
    }
    else{
      uiItems.push(
          <article id="article">
            <h2 id="title">My ML Projects</h2>
            <div id="options">
              <ul>
                <li><button id="about" onClick={(e) => this.update_menu_item(1)}>About</button></li>
                <li><button id="face_emotion_detection" onClick={(e) => this.update_menu_item(2)}>Face Emotion Detection</button></li>
                <li><button className="active"  id="military_detection" onClick={(e) => this.update_menu_item(3)}>Military Detection</button></li>
              </ul>
            </div>

            <p>The aim of this project is to detect military personnel from an input data. The input can be a picture or a video, however for this WebApp, currently it is supported only images input. If you would like to test the video feature, check out the git repository. Upload a picture with military personnel and see how the model works:</p>
            <input
              type="file"
              name="picture"
              id="picture"
              placeholder="Upload a Picture with Military"
              onChange={this.fileSelect}
            />
            <input
              type="button"
              value="submit"
              onClick={(e) => this.uploadMilitary()}
            />
          </article>
        )
    }

    return uiItems;
  }

  render(){
    return(
      <main>
        

        {this.generate_segment()}
      </main>
    );
  }
}

export default App;

API returns 一个简单的字符串和一张保存在SSD上的图片:

API 视图:

@api_view(['PUT'])
def obtainFaceEmotionPrediction(request):
    if request.method == 'PUT':
        if request.FILES.get("image", None) is not None:
            img = request.FILES["image"]
            img = img.read()
            model = FaceEmotionRecognition()
            img = model.detect_emotion(img)

            dir = '../frontend/public/pictures_saved/face_emotion/'
            for f in os.listdir(dir):
                os.remove(os.path.join(dir, f))

            cv2.imwrite('../frontend/public/pictures_saved/face_emotion/face_emotion_1.png', img)
            return Response({'file': 'face_emotion_1.png'})

控制台中出现 1 个错误和 1 个警告,但我似乎无法理解它们是否与问题有关:

此外,API 调用顺利进行:

我尝试过以不同的方式编写和重写代码。我尝试使用 event.preventDefault() 和其他变体,但似乎没有任何效果。我想补充的是,当前代码可以正常工作,并且完全按照我的要求执行,只是它会重新加载页面。

非常感谢你的帮助。

我解决了这个问题。问题出在 API,更具体地说:

cv2.imwrite('../frontend/public/pictures_saved/face_emotion/face_emotion_1.png', img)

基本上,在 Django 服务器中,我将图片保存到 React 服务器文件中。 React“看到”文件发生了变化(新文件 added/modified。不一定要编辑 .js 或 .css。只需添加一个简单的 .png)和 re-rendered 整个文件页。为什么它会这样工作?我没有任何线索。我将保存图像的路径更改为在 React 的服务器文件之外,它非常有效。