【问题标题】:Redux how to open a new window after ajax completeRedux如何在ajax完成后打开一个新窗口
【发布时间】:2016-01-08 11:32:34
【问题描述】:

这是我的问题:

我在表单上有一个保存按钮。单击保存按钮时,它应该通过 ajax 发送表单数据。 ajax 调用成功后,应该会打开一个新窗口。

我遇到的问题是这样的(我使用的是 React + Redux):

//inside the component class
handleSubmit = (e) => {
    this.props.dispatch( // calls ajax )
}


//inside the ajax action
dispatch => {
    fetch(...).then(response => {
        if (res.status >= 200 && res.status < 300) {
            window.open(...)
        }
    })
}

window.open() 放入ajax 调用的问题是新窗口将被视为被chrome 和FF 阻止的弹出窗口。

我认为我应该将window.open() 放在handleSubmit 中,以防止浏览器阻止它。但是如何确定dispatch 是否在handleSubmit 内部成功完成?或者有没有其他地方可以拨打window.open()而不会被屏蔽?

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    一旦promise 命中.then(),就调度另一个触发window.open 的操作,AJAX 请求已经完成,因为promise 现在已解决。

    function openWindow(someData) {
        const url = someData.url;
        window.open(url);
        return { type: 'SOME_ACTION_TO_TAKE' };
    }
    
    export function someAction() {
      let endpoint = 'http://localhost:8000/myEndpoint/';
      return dispatch => {
        return Axios.post(endpoint)
          .then(response => response.data)
          .then(json => dispatch(openWindow(json)))
          .catch((err) => { //Do whatever to error here }); 
      };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-20
      • 2013-03-30
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多