首页 > 解决方案 > 同时执行两个方法

问题描述

目标:
当您按下“回家!”按钮时 您应该执行代码“fetch( https://jsonplaceholder.typicode.com/users)”,然后被推送到“/home”

问题:
如何应用按钮可以同时执行提取和推送?

信息:
*我是 React JS 的新手

Stackblitz:
https ://stackblitz.com/edit/react-router-history-push-yux12z?file=components/User.js

import React from "react";
export class User extends React.Component {
  
  fetchUsers() {
    fetch(`https://jsonplaceholder.typicode.com/users`)
      .then(response => response.json())
      .then(data =>
        this.setState({
          users: data,
          isLoading: false
        })
      )
      .catch(error => this.setState({ error, isLoading: false }));
  }

  render() {
    return (
      <div>
        <h3>THE USER PAGE</h3>
        <p>USER ID: {this.props.match.params.id}</p>
        <button
          onClick={() => {
            this.props.history.push("/home");
          }}
        >
          GO HOME!
        </button>
      </div>
    );
  }
}

标签: javascriptreactjs

解决方案


setSate 函数接受另一个可选输入,即在状态更新后执行的函数。

import React from "react";
export class User extends React.Component {
  
  fetchUsers() {
    fetch(`https://jsonplaceholder.typicode.com/users`)
      .then(response => response.json())
      .then(data =>
        this.setState({
          users: data,
          isLoading: false
        }, () => {
                // this will be executed after the state was updated
                // the data was fetched and the state was update
                  this.props.history.push("/home")
         })
      )
      .catch(error => this.setState({ error, isLoading: false }, ()=>{
                  // the state was updated, you can redirect to home or an error page
                  this.props.history.push("/home")
       }));
  }

  render() {
    return (
      <div>
        <h3>THE USER PAGE</h3>
        <p>USER ID: {this.props.match.params.id}</p>
        <button
          onClick={this.fetchUsers.bind(this)}
        >
          GO HOME!
        </button>
      </div>
    );
  }
}

推荐阅读