1.redux
核心概念:
1、store(仓库):(1)state数据(2)reducer处理器
2、dispatch(动作发送器)
3、action动作
4、在组件中沟通过dispatch发送动作触发仓库中的reducer处理并返回最新的state数据
01、创建仓库
(1)import{storeConfigure} from '@reduxjs/toolkit'
(2)import counter from './counterSlice'
(3)export const store = storeConfigure({
reducer:{counter}
})
02、全局注入(main.js)
(1)import {store} from './store/index.js'
import {Provider} from 'react-redux'
(2)<Provider store={store}>
<App/>
</Provider>
03、创建切片(store/counterSlice.js)
(1)import {createSlice} from '@reduxjs/toolkit'
(2)const initialState = {value:0}
(3)const counterSlice = createSlice({
name:"counter",
initialState,
reducers:{
increment:state=>{state.value+=1},
decrement:state=>{state.value-=1},
addValue:(state,action)=>
{state.value+=action.paylod}
}
})
(4)export const {increment,decrement,addValue}=counterSlice.actions
(5)export default counterSlice.reducer
(6)export syncAddValue = (value) => (dispatch) => {
setTimeout(() => {
dispatch(addValue(value))
}, 2000)
}
04、使用redux
(1)import {useSelector,useDispatch} from 'react-redux'
import { increment, decrement, addValue, syncAddValue } from '../../store/counterSlice';
(2)const value = useSelector(state=>state.counter.value
(3)const dispatch = useDispatch();
(4)dispatch(increment())
发送动作
2.react-router-dom(路由)
概念:监听地址栏变化,不刷新页面,动态切换div模拟切换页面
安装: npm i react-router-dom -S
1、使用步骤
(1) 创建页面
src/views/HomeView.jsx
src/views/AboutView.jsx
(2) 配置路由
src/router/index.jsx
const routes = [
{path:"/",element:<HomeView/>},
{path:"/about",element:<AboutView/>}
]
03 创建路由
src/router/index.jsx
export default function RouterView(){
const elem = useRoutes(routes)//路由配置
return elem
}
04 05 使用并切换路由
App.jsx
<HashRouter>
<NavLink to="/">首页</NavLink>
<NavLink to="/about">关于</NavLink>
<RouterView />
</HashRouter>
2、路由组件与方法
1、组件
(1)<HashRouter> 哈希路由
(2)<BrowserRouter> 浏览器路由
(3)<NavLink> 导航链接
选中会有active 类名
(4)<Link>导航链接
(5)<OutLet>子路由容器
2、方法
(1)useRoutes使用路由配置
(2)useParams() 路由参数
(3)useSearchParams() 获取查询参数
3、路由参数
(1)<NavLink to="/produce/123"
(2)router/index.jsx
{path:"/produce/:id",element:<ProduceView/>}
(3)在ProductView.jsx
const {id} = useParams();
4、路由查询参数
(1)<NavLink to="/about?redirect=hello"
(2)不需要配置
(3)在About.jsx
const [searchParams] = useSearchParams();
const redirect = searchParams.get("reidrect")
5、子路由
(1)router/index.jsx
{path:"/admin",element:<AdminView/> ,children:
[{path:"",element:<DashView/>},
{path:"orderlist",element:<OrderList/>}
]
}
(2)views/admin/adminView.jsx
<Link to="">概览</Link> | <Link to="orderlist">订单</Link> |
<Outlet/>
(3)404
配置在最后面
{path:"*",element:<div>404</div>}