Redux如何在ajax完成后打开一个新窗口

Redux how to open a new window after ajax complete

本文关键字:一个 窗口 新窗口 ajax Redux      更新时间:2023-09-26

这是我的问题:

我在表单上有一个保存按钮。当点击保存按钮时,它应该通过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()而不会被屏蔽吗?

调度另一个触发窗口的操作。一旦promise命中.then(),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 }); 
  };
}