React:只有在第一部分完全完成后才执行后面的函数

杰杰恩

我有一个函数 fetchTweets,它使用给定的参数 a 和 b 获取推文。

函数 toPageTwo 调用 fetchTweets 函数,然后将用户重定向到另一个显示获取数据的页面

toPageTwo() {
      this.fetchTweets(param1,param2);
      this.props.router.push(`/page2`);
    }
}

当用户单击发送按钮时,toPageTwo() 正在执行:

<Button onClick={::this.toPageTwo}>
Send
</Button>

如何确保仅在正确获取推文后才加载 page2?

更新:

我正在使用 Redux 和 Axios 来获取推文,并且开始获取等的按钮位于侧边栏中。我的文件树如下所示:

src
  redux
    actions
      tweets.js
  common
    sidebar.js

推文.js:

import axios from "axios";

export function fetchTweets(a,b){
    return function(dispatch) {
        axios.get("http://127.0.0.1:5000/?a="+a+"&b="+b)
        .then((response) => {
            dispatch({type: "FETCH_TWEETS_FULFILLED", payload: response.data})
        })
        .catch((err) => {
            dispatch({type: "FETCH_TWEETS_REJECTED", payload: err})
        })
    }
}

如果我将“.then”添加到 FETCH_TWEETS_FULFILLED 调度,我可以在获取后控制台日志。但是这不适用于 this.props.router.push( /page2)

sidebar.js:

-- IMPORTS --
@connect((state) => state)

@withRouter
class ApplicationSidebar extends React.Component {

    -- BUNCH OF FUNCTIONS --

    fetchTweets(a,b) {
      this.props.dispatch(fetchTweets(a,b));
    }

    toPageTwo() {
          fetchTweets(param_a,param_b);
          this.props.router.push(`/page2`);
        }
    }


    render() {
        return (
            -- SIDEBAR STUFF --

                <Button onClick={::this.toPageTwo}>
                Send
                </Button>

        );
     }

出于某种原因,创建回调函数的结果与常规函数的结果相同:后一个函数在第一部分(推文获取)完成之前执行。

谢谢!

斯特凡·瑟德

我认为修改fetchTweets以接受回调将是最好的方法。

例如。

import axios from "axios";

export function fetchTweets(a,b, callback){
    return function(dispatch) {
        axios.get("http://127.0.0.1:5000/?a="+a+"&b="+b)
        .then((response) => {
            dispatch({type: "FETCH_TWEETS_FULFILLED", payload: response.data})
            callback()
        })
        .catch((err) => {
            dispatch({type: "FETCH_TWEETS_REJECTED", payload: err})
        })
    }
}

-- IMPORTS --
@connect((state) => state)

@withRouter
class ApplicationSidebar extends React.Component {

-- BUNCH OF FUNCTIONS --

    fetchTweets(a,b, callback) {
      this.props.dispatch(fetchTweets(a,b, callback));
    }

现在这里是您传递匿名函数作为回调的地方,例如。

    toPageTwo() {
          fetchTweets(param_a,param_b, () => {this.props.router.push(`/page2`));
        }
    }


    render() {
        return (
            -- SIDEBAR STUFF --

                <Button onClick={::this.toPageTwo}>
                Send
                </Button>

        );
     }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章