无法设法获取响应(React)

时间:2017-05-23 12:29:56

标签: reactjs response fetch

我尝试了各种各样的组合,但都没有效果。有什么想法吗?

  handleSubmit(event) {
    let newsletter = 'https://domain.us0.list-manage.com/subscribe/post-json?u=00000&id=00000';
    let email = '&EMAIL=' + this.state.value;
    fetch(newsletter + email, {
      mode: 'no-cors',
    })
    .then(function(response) {
      return response.json().then(data => this.setState({message: data.msg}));
    });
    console.log(this.state.message);
    console.log(this.state.value);
    event.preventDefault();
  }

我得到的错误是:

Uncaught (in promise) SyntaxError: Unexpected end of input
    at App.js:35
    at <anonymous>

在网络标签中,一切正常。我收到了以下回复:

{"result":"error","msg":"user@gmail.com is already subscribed to list."}

1 个答案:

答案 0 :(得分:0)

我将以不同的方式构造和使用Promise,您可以按照以下方式执行操作,使代码更具可读性:

handleSubmit(event) {
  event.preventDefault();
  let newsletter = 'https://domain.us0.list-manage.com/subscribe/post-json?u=00000&id=00000';
  let email = `&EMAIL=${this.state.value}`;

  fetch(`${newsletter}${email}`, { method: 'GET', mode: 'no-cors' })
    .then(response => response.json())
    .then(data => {
      // Here you can also handle errors
      if (data.result === 'error') {
        // Handle Error
      } else {
        this.setState({ message: data.msg });
      }

      console.log(this.state.message);
      console.log(this.state.value);
    })
    .catch(err => console.log(err));

  // Keep in mind that these console statements might
  // execute before your Promise is resolved, thus
  // referring to the state before the request
  // has been fulfilled. For this reason I commented them out
  // console.log(this.state.message);
  // console.log(this.state.value);
}

我注意到你使用了function=>的混合物,所以我建议选择其中一个,除非你有特殊的理由使用其中一个。

我担心您第一次使用function这一事实会创建一个新的上下文,以便this现在引用您转换为{{1}的函数内的任何this因为你不想在这个场景中创建新的上下文,所以坚持使用箭头函数。

这是我在处理AJAX请求时通常遵循的一种方法,因为第一个json返回.then,您可以链接另一个Promise,它可以处理结果前一个。它更容易阅读和调试。

相关问题