问题
I am working in a Web application (built using React+Redux+React Router Dom) and Firebase as backend.
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:
Yes it is possible:
1-) create a history.js file with this content.
import createHistory from "history/createBrowserHistory";
export default createHistory();
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-) 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");
});
};
};
回答2:
You can just use/try this if it's just a simple redirect.
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(()=>{
window.location.href = url
})
}
}
来源:https://stackoverflow.com/questions/58588303/react-router-dom-redirect-from-redux-action-creator