第一步:安装redux插件 npm i react-redux@7
创建store文件,定义数据、以及操作数据方法,并导出
import {createStore} from "redux" //引入 createStore const rendues=(state,actions)=>{ if(!state){//初始数据 return{ num:1 } } const {type,payload}=actions switch(type){ //定义方法 case "Add-num": let nums=state.num nums+=1 state.num=nums console.log('state', state) return {...state} break; default: return state break; } } const score=createStore(rendues) export default score
App.js页面
import React, { Suspense } from "react" import './App.css'; import { Provider } from "react-redux" import { BrowserRouter, Route, Routes, useNavigate } from "react-router-dom" import Errcon from './errcon'; import Loading from "./Loading"; import score from "./store/one1/index"; const Main = React.lazy(() => import("./views/one1/main")) function App() { // const Navigate = useNavigate() return ( <div> <Suspense fallback={<Loading />}> <Provider store={score}> <BrowserRouter> <Routes> <Route path='/' element={<Main />}></Route> <Route path='/err' element={<Errcon />}></Route> {/* <Route path="*" element={<Navigate to="/err" replace={true}/>} /> */} </Routes> </BrowserRouter> </Provider> </Suspense> </div> ); } export default App;
该代码中:
Suspense用于页面的懒加载,结合react中的lazy属性一起使用。
Provider 包裹在根组件外层,使所有的子组件都可以拿到state
子页面
import React, { useState } from 'react' import "../css/main.css" import { connect } from "react-redux" function Main(props) { const con=props.count console.log('con', con) console.log('props', props) const addnum = () => { props.add(); console.log('conss', props.count); }; return ( <div className='main'> <h2>main</h2> <p>{con.num}</p> <button onClick={addnum}>添加</button>- <button>减少</button> </div> ) } const mapStateToProps = (state) => { return { count: state } } const mapDispatchToProps = (dispatch ) => { return { add: () =>dispatch ({ type: "Add-num" }) } } export default connect(mapStateToProps , mapDispatchToProps )(Main)