React - 组件

时间:2017-09-15 20:00:40

标签: javascript reactjs meteor callback

我正在尝试创建一个从api获取回调的应用程序,然后在函数中返回它(我不知道这是否有意义)。但是我怎么做到这一点,当我调用该函数时,我将一个回调附加到它上面,然后返回回调数据。当我输入我的代码时,尝试描述它是非常令人困惑的。

uploadToCloudinary(file){
    const CLOUDINARY_URL = "MY_CLOUDINARY_URL";
    const CLOUDIARY_UPLOAD_PRESET = "MY_CLOUDIARY_UPLOAD_PRESET"
    let formData = new FormData();

    formData.append("file", file);
    formData.append("upload_preset", CLOUDIARY_UPLOAD_PRESET)

    axios({
      url: CLOUDINARY_URL,
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: formData
    }).then(function(res){
      callback(new Meteor.Error(400, "Error"), res);
    }).catch(function(err){
      console.log(err);
    })
    console.log(file);
  }

所以这里我正在做的是我获取文件参数并将其输入到cloudinary(文件处理api)并尝试在收到数据时进行回调。我理解回调的概念(sorta)以及如何使用它们,但我不确定如何使函数有回调。

  addNote(e){
    e.preventDefault();
    let title = this.refs.title.value;
    let subject = this.refs.subject.value;
    let description = this.refs.description.value;
    let allUrls = [this.refs.imageURL.value].concat(this.state.urls);
    let imageURL = allUrls.filter(function(entry) { return entry.trim() != ''; });
    let userId = Meteor.userId();
    let userEmail = Meteor.user().emails[0].address;
    let createdAt = Date.parse(new Date());
    let unit = this.refs.unit.value;
    let file = this.refs.fileInput.files[0];

    if(!Meteor.userId()){
      this.setState({
        message: "You need to login before you can add a note",
        loginMessage: <Link to="/login">Login</Link>
      })
      throw new Meteor.Error(400, "User is not signed in.")
    }

    if(title && subject && description && unit){
      if(imageURL || file){
          let noteInfo = { title, subject, description, imageURL, userId, userEmail, createdAt, unit };
          this.uploadToCloudinary(file, (err, res) => {
            console.log(res)
          });
          //need to make a callback for this^^^^ (ln 52)
          Meteor.call("notes.insert", noteInfo, (err, res) => {
            if(err){
              this.setState({message: err.reason});
              console.log(err)
            }else{
              this.props.history.push("/")
            }
          })
        }else {
          this.setState({ message: "You must fill in all the blanks.  " })
        }
      }
  }

这是我试图调用该函数的地方,希望得到错误/响应。所以我的问题是如何在react组件中进行回调?我一直收到callback is not defined的错误。

2 个答案:

答案 0 :(得分:1)

嘿,你所做的并不是完全错误的,而不是委托你如何处理请求的责任,你可以从上传功能返回承诺,然后为然后捕获。是否有意义?然后,您可以自己管理来自服务器的内容并相应地更新状态。如果有帮助我可以给你写一个代码示例让我知道。除此之外,您的错误是因为您没有将回调作为参数传递

答案 1 :(得分:0)

您的错误来自这段代码:

axios({
    url: CLOUDINARY_URL,
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    data: formData
}).then(function(res){

    // Right here...callback hasn't been defined anywhere
    callback(new Meteor.Error(400, "Error"), res);

}).catch(function(err){
    console.log(err);
});

您似乎只需要更新uploadToCloudinary函数参数以接受回调:

// Add a second param here
uploadToCloudinary(file, callback){
    const CLOUDINARY_URL = "MY_CLOUDINARY_URL";
    const CLOUDIARY_UPLOAD_PRESET = "MY_CLOUDIARY_UPLOAD_PRESET"
    let formData = new FormData();

    formData.append("file", file);
    formData.append("upload_preset", CLOUDIARY_UPLOAD_PRESET)

    axios({
        url: CLOUDINARY_URL,
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        },
        data: formData
    }).then(function(res){
        callback(new Meteor.Error(400, "Error"), res);
    }).catch(function(err){
        console.log(err);
    })
    console.log(file);
}