在RE上使用带有异步/等待的React类字段的RE问题

时间:2019-07-25 03:49:09

标签: reactjs async-await

使用React的Class Fields语法时,如何为我的“事件”(markComplete,addTodo)使用async / await和try / catch on箭头功能?

仅使用构造函数并在其中绑定自定义方法比使用类字段和箭头函数更好吗?

class App extends Component {
  state = {
    todos: [],
  };

  // async/await here, I understand
  async componentDidMount() {
    try {
      const res = await axios.get(
        'http://jsonplaceholder.typicode.com/todos?_limit=10'
      );
      const data = await res.data;
      this.setState({
        todos: data,
      });
    } catch (err) {
      console.error(err);
    }
  }

  // Q: how can I use async/await and try/catch here?
  markComplete = id => {
    this.setState({
      todos: this.state.todos.map(todo => {
        if (todo.id === id) {
          todo.completed = !todo.completed;
        }
        return todo;
      }),
    });
  };

  // Q: how can I use async await and try/catch here?
  addTodo = title => {
    axios
      .post('http://jsonplaceholder.typicode.com/todos', {
        title,
        completed: false,
      })
      .then(res =>
        this.setState({
          todos: [...this.state.todos, res.data],
        })
      );
  };

  render() {
    return (
      <Router>...</Router>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

您还可以使箭头功能异步。

addTodo = async title => {
  try {
    await axios.post('http://jsonplaceholder.typicode.com/todos', { title, completed: false, })
    .then(res => this.setState({ todos: [...this.state.todos, res.data] }));
  } catch(err) {
    // Handle err
  }
};

从axios返回的诺言中您所拥有的一切都很好,您可以在诺言链中添加一个catch块。

addTodo = async title => {
  await axios.post(
    'http://jsonplaceholder.typicode.com/todos',
    { title, completed: false, }
  )
  .then(res => this.setState({ todos: [...this.state.todos, res.data] }))
  .catch(err => {
    // Handle err
  });
};