在React Redux中,当路由更改时维护全局状态可以通过以下步骤实现:
npm install react-router-dom react-redux
routes.js
。在该文件中,定义应用的各个路由,并将它们与对应的组件关联起来。例如:import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
import Contact from './components/Contact';
const Routes = () => (
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
);
export default Routes;
routerReducer.js
的文件,并编写以下代码:import { LOCATION_CHANGE } from 'react-router-redux';
const initialState = {
location: null
};
const routerReducer = (state = initialState, action) => {
switch (action.type) {
case LOCATION_CHANGE:
return {
...state,
location: action.payload
};
default:
return state;
}
};
export default routerReducer;
routerReducer
添加到store中。然后,使用ConnectedRouter
组件将路由和store连接起来。例如:import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import { createBrowserHistory } from 'history';
import { createStore, combineReducers } from 'redux';
import Routes from './routes';
import routerReducer from './routerReducer';
const history = createBrowserHistory();
const rootReducer = combineReducers({
router: routerReducer
});
const store = createStore(rootReducer);
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Routes />
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
react-redux
库提供的connect
函数,将组件连接到store,并将全局状态作为props传递给组件。例如,在一个名为App.js
的组件中,可以这样使用全局状态:import React from 'react';
import { connect } from 'react-redux';
const App = (props) => {
const { location } = props.router;
// 在这里可以使用location来根据路由更改做一些全局状态的操作
return (
<div>
{/* 组件的内容 */}
</div>
);
};
const mapStateToProps = (state) => ({
router: state.router
});
export default connect(mapStateToProps)(App);
通过以上步骤,我们可以在React Redux中实现在路由更改时维护全局状态。这样,当路由发生变化时,我们可以在全局状态中更新相关数据,并在组件中使用这些数据来进行相应的操作。
推荐的腾讯云相关产品:腾讯云服务器(CVM)和腾讯云数据库(TencentDB)可以用于部署和存储React Redux应用程序。您可以在腾讯云官网上找到更多关于这些产品的详细信息和介绍。
腾讯云服务器(CVM)产品介绍链接:https://cloud.tencent.com/product/cvm
腾讯云数据库(TencentDB)产品介绍链接:https://cloud.tencent.com/product/cdb
领取专属 10元无门槛券
手把手带您无忧上云