使用 Redux 在 React 中进行编程式路由 Routing programmatically in react with redux refers to the process of navigating between different components or pages in a React application using Redux. This means that instead of using traditional URL-based routing, the navig
使用 Redux 在 React 中进行编程式路由 Routing programmatically in react with redux refers to the process of navigating between different components or pages in a React application using Redux. This means that instead of using traditional URL-based routing, the navig
下面的index.js代码片段在我想要从页面上的静态链接进行路由时很好用:
import React from 'react'; import ReactDOM from 'react-dom'; import LoginForm from './components/LoginForm/LoginForm'; import { Provider } from 'react-redux'; import store from './redux/store'; import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'; import Home from './components/Home.js' ReactDOM.render(, document.getElementById('root') ); My Page
- LoginForm
- Home
是否有办法在代码中路由到另一个页面,像这样?
updateStore(loggedIn){ const action = {type:loggedIn}; store.dispatch(action); if(loggedIn==='LOGGED_IN'){ console.log("I am In"); // 路由到另一个页面?? }else{ console.log("I am out"); } }
在React中使用Redux进行编程式路由的原因是为了在action中能够使用路由跳转功能。解决方法是创建一个route.js文件来定义路由,然后在index.js中引入这个route.js文件并使用Router组件来包裹RouteList组件。最后,在action.js中引入上一步创建的history对象,使用history.push('/home')来实现路由跳转。
下面是具体的代码实现:
首先,创建一个名为route.js的文件,并在其中定义路由组件RouteList:
import React from 'react'; import { Route, Switch } from 'react-router'; import LoginForm from './components/LoginForm/LoginForm'; import Home from './components/Home'; class RouteList extends React.Component { render() { return (); } } export default RouteList;
然后,在index.js文件中引入route.js文件,并使用Router组件将RouteList组件包裹起来:
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import store from './redux/store'; import RouteList from './route'; import { Router } from 'react-router' import createBrowserHistory from 'history/createBrowserHistory' export const history = createBrowserHistory() ReactDOM.render(, document.getElementById('root') );
最后,在action.js文件中引入上一步创建的history对象,并在适当的位置使用history.push('/home')来实现路由跳转:
import { history } from '../index'; callLoginApi(email, password, error => { dispatch(setLoginPending(false)); if (!error) { dispatch(setLoginSuccess(true)); history.push('/home'); } else { dispatch(setLoginError(error)); } });
通过以上步骤,我们可以在action中使用Redux进行编程式路由跳转。