从 redux 动作创建者反应路由器 Dom 重定向 [英] React Router Dom redirect from redux action creator
问题描述
我正在使用 Web 应用程序(使用 React+Redux+React Router Dom 构建)和 Firebase 作为后端.
I am working in a Web application (built using React+Redux+React Router Dom) and Firebase as backend.
我的问题是:是否可以从动作创建者(因此,在反应路由器 dom 组件之外)执行重定向?
My question is: Is possibile to carry out a Redirect from an action creator (so, outside the react router dom components ) ?
例如:我希望用户在删除项目后被重定向到主页:
For example: I want user to be redirected to Home after an operation of deletion of an item:
export const deleteItem = (item) =>{
const id = firebase.auth().currentUser.uid;
var itemRef = firebase.database().ref("users/"+id+"/items/"+item);
return dispatch =>{
dispatch({type:'DELETING_ITEM'});
item.remove()
.then(()=>{
// I WANT TO REDIRECT USER TO /HOME (or anywhere else)
})
}
}
如何以编程方式实现重定向?
How can achieve a redirect programmatically ?
推荐答案
是的,这是可能的:
1-) 使用此内容创建一个 history.js 文件.
1-) create a history.js file with this content.
import createHistory from "history/createBrowserHistory";
export default createHistory();
2-) 在您设置路由器的文件中(在 index.js 或 app.js 中):使用 react-router-dom 中的 Router 而不是 BrowserRouter,导入历史并将其添加到 Router 的 history prop 中,如下所示:
2-) in the file you set up Router (in index.js or app.js): use Router from react-router-dom instead of BrowserRouter, import history and give it in history prop of Router like this:
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import * as serviceWorker from "./serviceWorker";
import { Router } from "react-router-dom";
import history from "./history";
import { Provider } from "react-redux";
import store from "./store/store";
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>,
document.getElementById("root")
);
3-) 在你的行动中使用它
3-) use it in your action
import history from "../../history";
export const deleteItem = item => {
const id = firebase.auth().currentUser.uid;
var itemRef = firebase.database().ref("users/" + id + "/items/" + item);
return dispatch => {
dispatch({ type: "DELETING_ITEM" });
item.remove().then(() => {
// I WANT TO REDIRECT USER TO /HOME (or anywhere else)
history.push("/home");
});
};
};
这篇关于从 redux 动作创建者反应路由器 Dom 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!