【问题标题】:I don't know how to get data from fetch correctly我不知道如何正确地从 fetch 中获取数据
【发布时间】:2020-10-04 03:03:05
【问题描述】:

我有一个用户类,我想从服务器获取数据,以便稍后将其写入状态并将数据从状态传递到子组件

export default class Users extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: this.getUsers(),
    };
  }

  getUsers = async () => {
    await return fetch(`http://localhost:3001/users`, {
      method: 'POST',
      accept: 'application/json'
    }).then(res => {
      if(res.ok) {
        res.json();
      }
    })
  }
}

这是当我输出有关 this.state.users 的数据时控制台向我显示的内容

我试图寻找类似的情况,但我没有找到任何有价值的东西,所以我在这里寻求帮助。我将不胜感激任何建议或帮助。我只是在js中学习异步

【问题讨论】:

标签: javascript reactjs async-await react-redux fetch


【解决方案1】:

如果您使用异步等待,则不必传递回调函数,只需 await 承诺并在成功响应时更新状态。

getUsers = async () => {
    try {
       const response =  await fetch(`http://localhost:3001/users`, {
         method: 'POST',
         accept: 'application/json'
       });

       const users = await response.json();

       this.setState({ users });

     } catch (error) {
       console.log(error);
    }
 }

不要从构造函数调用getUsers函数,而是使用componentDidMount

componentDidMount() {
    this.getUsers();
}

并且您的状态最初应该为 null 或空数组

this.state = {
  users: []
};

【讨论】:

  • 感谢您的帮助,您很好地解释并解决了我的问题。
  • this.getUsers(); inside componentDidMount 将抛出未处理的异常,如果请求失败。
  • @JuniusL。 getUsers 函数内的 try-catch 块不是处理异常吗?我刚刚添加了 console.log 语句,但 OP 可以从 catch 块创建一个新的状态变量,以防出现错误。
【解决方案2】:

添加 componentDidMount 并调用 getUsers 并设置状态。

this.state = {
  users: [],
};

getUsers = async () => {
  return await fetch(`http://localhost:3001/users`, {
    method: 'POST',
    accept: 'application/json'
  }).then(response => response.json())
   .then(res => { this.seState({ users: res })})
   .catch(e => { console.log(e)})
}

componentDidMount = () => {
  this.getUsers()
    .catch(e => console.log(e)
}

【讨论】:

    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    相关资源
    最近更新 更多