面试题答案
一键面试1. 安装依赖
首先确保项目中安装了 redux
和 react - redux
:
npm install redux react-redux
2. 定义 Action Types
在Redux中,我们先定义用于路由相关操作的action types,比如切换路由:
// actionTypes.js
export const SET_CURRENT_ROUTE = 'SET_CURRENT_ROUTE';
export const TOGGLE_PAGE_ANIMATION = 'TOGGLE_PAGE_ANIMATION';
3. 定义 Actions
接下来定义action creators,它们返回描述操作的对象:
// actions.js
import { SET_CURRENT_ROUTE, TOGGLE_PAGE_ANIMATION } from './actionTypes';
export const setCurrentRoute = (route) => ({
type: SET_CURRENT_ROUTE,
payload: route
});
export const togglePageAnimation = () => ({
type: TOGGLE_PAGE_ANIMATION
});
4. 定义 Reducer
Reducer根据接收到的action来更新state:
// reducer.js
import { SET_CURRENT_ROUTE, TOGGLE_PAGE_ANIMATION } from './actionTypes';
const initialState = {
currentRoute: '/',
isPageAnimating: false
};
const routeReducer = (state = initialState, action) => {
switch (action.type) {
case SET_CURRENT_ROUTE:
return {
...state,
currentRoute: action.payload
};
case TOGGLE_PAGE_ANIMATION:
return {
...state,
isPageAnimating:!state.isPageAnimating
};
default:
return state;
}
};
export default routeReducer;
5. 创建 Store
使用 createStore
来创建Redux store:
// store.js
import { createStore } from'redux';
import routeReducer from './reducer';
const store = createStore(routeReducer);
export default store;
6. 连接 React 组件到 Redux
在React组件中使用 react - redux
的 connect
方法(或者 useSelector
和 useDispatch
hooks)来连接组件到Redux store,这里以 useSelector
和 useDispatch
为例:
import React from'react';
import { useSelector, useDispatch } from'react-redux';
import { setCurrentRoute, togglePageAnimation } from './actions';
const App = () => {
const currentRoute = useSelector(state => state.currentRoute);
const isPageAnimating = useSelector(state => state.isPageAnimating);
const dispatch = useDispatch();
const handleRouteChange = (newRoute) => {
dispatch(setCurrentRoute(newRoute));
dispatch(togglePageAnimation());
};
return (
<div>
{/* 这里处理路由切换逻辑,比如使用 <Link> 组件 */}
<button onClick={() => handleRouteChange('/new - route')}>切换路由</button>
<p>当前路由: {currentRoute}</p>
<p>页面是否正在动画: {isPageAnimating? '是' : '否'}</p>
</div>
);
};
export default App;
7. 在React Router中集成
结合React Router,可以在路由切换时触发Redux actions:
import React from'react';
import { BrowserRouter as Router, Routes, Route, Link } from'react-router-dom';
import { useDispatch } from'react-redux';
import { setCurrentRoute, togglePageAnimation } from './actions';
const Home = () => <div>Home Page</div>;
const About = () => <div>About Page</div>;
const App = () => {
const dispatch = useDispatch();
const handleRouteChange = (newRoute) => {
dispatch(setCurrentRoute(newRoute));
dispatch(togglePageAnimation());
};
return (
<Router>
<div>
<nav>
<Link to="/" onClick={() => handleRouteChange('/')}>Home</Link>
<Link to="/about" onClick={() => handleRouteChange('/about')}>About</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
</Router>
);
};
export default App;
通过以上步骤,我们可以在React项目中利用Redux有效地管理路由切换时的相关状态。