我可以在一个组件中做多次反应吗?

时间:2018-04-12 17:54:08

标签: javascript reactjs express

我正在使用react作为我的前端,并将express.js作为我的后端。我对两个框架都不熟悉。我有一个名为Papers的组件,我试图首先通过fetch post将一些文档上传到后端服务器,然后在服务器端执行一些操作,然后我试图从同一个处理程序中的服务器返回结果。我的处理程序代码如下所示:

        handleDrop(files) {
          var data = new FormData();

          alert((files[0]) instanceof File);
          files.forEach((file, index) => {
            data.append('file' + index, file);
          });

          fetch('/file_upload', {
            method: 'POST',
            body: data
          });

          // the second fetch would crash the app.
          /*fetch('/file_upload').then(function(data){
              return data.json();
          }).then( json => {
              this.setState({
                  papers: json
              });
              console.log(json);
          });*/
        }

我对get方法的快速后端代码是:

app.get('/file_upload', function(req, res){
    // testing
    res.send({name:"lol"});
});

现在的问题是第二次获取会使快递应用程序崩溃。由于我是新手做出反应和表达,如果我以正确的方式做这件事,有人可以给我一些提示吗?谢谢!

指向服务器代码的链接:https://github.com/kaiwenshi/learn-webpack/blob/master/src/server/index.js

1 个答案:

答案 0 :(得分:0)

如果要进行POST,Express代码应如下所示:

app.post('/file_upload', function(req, res){
    // testing
    res.send({name:"lol"});
});

你只需要进行一次fetch调用。响应({name: 'lol'})将在承诺中:

    handleDrop(files) {
      var data = new FormData();

      alert((files[0]) instanceof File);
      files.forEach((file, index) => {
        data.append('file' + index, file);
      });

      fetch('/file_upload', {
        method: 'POST',
        body: data
      }).then(function(data){
          return data.json();
      }).then( json => {
          this.setState({
              papers: json
          });
          console.log(json); // logs {name: 'lol'}
      });
    }