first commit

main
expressgy 10 months ago
commit 92db158999
  1. 21
      .eslintrc.cjs
  2. 24
      .gitignore
  3. 8
      README.md
  4. 26
      index.html
  5. 30
      package.json
  6. 2543
      pnpm-lock.yaml
  7. 100
      public/loading.css
  8. 48
      public/reset.css
  9. 1
      public/vite.svg
  10. 13
      src/App.jsx
  11. 7
      src/Components/HtmlLoading/Eye/index.jsx
  12. 38
      src/Components/HtmlLoading/Eye/index.module.scss
  13. 6
      src/Components/HtmlLoading/One/index.jsx
  14. 51
      src/Components/HtmlLoading/One/index.module.scss
  15. 15
      src/Components/HtmlLoading/Pacman/index.jsx
  16. 123
      src/Components/HtmlLoading/Pacman/index.module.scss
  17. 9
      src/Components/HtmlLoading/TableTennis/index.jsx
  18. 65
      src/Components/HtmlLoading/TableTennis/index.module.scss
  19. 7
      src/Components/HtmlLoading/Three/index.jsx
  20. 34
      src/Components/HtmlLoading/Three/index.module.scss
  21. 8
      src/Components/HtmlLoading/Two/index.jsx
  22. 163
      src/Components/HtmlLoading/Two/index.module.scss
  23. 18
      src/Components/HtmlLoading/index.jsx
  24. 45
      src/main.jsx
  25. 18
      src/routes/PrivateRoute.jsx
  26. 37
      src/routes/index.jsx
  27. 23
      src/store/index.js
  28. 63
      src/store/slice/defaultSlice.js
  29. 24
      src/views/Test/index.jsx
  30. 1
      test/react-router-dom.md
  31. 314
      test/redux.md
  32. 17
      vite.config.js

@ -0,0 +1,21 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:react/jsx-runtime',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parserOptions: { ecmaVersion: 'latest', sourceType: 'module' },
settings: { react: { version: '18.2' } },
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
indent: [2, 4, { SwitchCase: 1 }],
},
}

24
.gitignore vendored

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

@ -0,0 +1,8 @@
# React + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

@ -0,0 +1,26 @@
<!doctype html>
<html lang="zh">
<head>
<script>
window.startime = new Date().getTime()
</script>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<link rel="stylesheet" href="/reset.css">
<link rel="stylesheet" href="/loading.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
</head>
<body>
<div id="root"></div>
<div id="loading">
<div id="upFace"></div>
<div id="downFace"></div>
<div id="loaderBox">
<div id="loader"></div>
<div id="loaderText">waiting</div>
</div>
</div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>

@ -0,0 +1,30 @@
{
"name": "react-template",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@reduxjs/toolkit": "^1.9.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.20.0",
"redux": "^4.2.1",
"sass": "^1.69.5"
},
"devDependencies": {
"@types/react": "^18.2.37",
"@types/react-dom": "^18.2.15",
"@vitejs/plugin-react": "^4.2.0",
"eslint": "^8.53.0",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.4",
"vite": "^5.0.0"
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,100 @@
body{
background: #111111;
}
#root{
position: relative;
background: #fefefe;
height: 100vh;
width: 100vw;
}
.openRoot{
animation: openRoot linear 1500ms;
}
#loading {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
min-height: 200px;
min-width: 200px;
display: flex;
align-items: center;
justify-content: center;
}
#loaderBox{
opacity: 1;
transition: opacity linear 1000ms;
}
.hideLoader{
opacity: 0 !important;
}
#upFace{
position: absolute;
height: 50%;
width: 100%;
top: 0;
left: 0;
background: #111;
transition: top linear 1500ms;
}
#downFace{
position: absolute;
height: 50%;
width: 100%;
bottom: 0;
left: 0;
background: #111;
transition: bottom linear 1500ms;
}
.upOpen{
top: -50vh !important;
}
.downOpen{
bottom: -50vh !important;
}
#loader {
position: relative;
width: 60px;
aspect-ratio: 2;
--_g: no-repeat radial-gradient(circle closest-side, #aaa 90%, #fff0);
background: var(--_g) 0% 50%, var(--_g) 50% 50%, var(--_g) 100% 50%;
background-size: calc(100% / 3) 50%;
animation: l3 1s infinite linear;
}
#loaderText{
position: relative;
text-align: center;
color: #fefefe;
line-height: 40px;
user-select: none;
color: #666;
}
@keyframes l3 {
20% {
background-position: 0% 0%, 50% 50%, 100% 50%;
}
40% {
background-position: 0% 100%, 50% 0%, 100% 50%;
}
60% {
background-position: 0% 50%, 50% 100%, 100% 0%;
}
80% {
background-position: 0% 50%, 50% 50%, 100% 100%;
}
}
@keyframes openRoot {
from{
transform: scale(0.7)
}
to{
transform: scale(1)
}
}

@ -0,0 +1,48 @@
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

@ -0,0 +1,13 @@
import {useRoutes} from "react-router-dom";
import routes from "@routes";
function App() {
const elements = useRoutes(routes)
return (
<>
{elements}
</>
)
}
export default App

@ -0,0 +1,7 @@
import css from './index.module.scss';
export default function Eye(){
return <div className={css.Eye}>
<div className={css.loader}></div>
</div>
}

@ -0,0 +1,38 @@
.Eye{
position: relative;
height: 200px;
width: 100%;
background: #333333;
display: flex;
align-items: center;
justify-content: center;
.loader {
display: inline-flex;
gap: 10px;
}
.loader:before,
.loader:after {
content: "";
height: 20px;
aspect-ratio: 1;
border-radius: 50%;
background: radial-gradient(farthest-side,#000 95%,#0000) 35% 35%/6px 6px no-repeat
#fff;
transform: scaleX(var(--s,1)) rotate(0deg);
animation: l6 1s infinite linear;
}
.loader:after {
--s: -1;
animation-delay: -0.1s;
}
@keyframes l6 {
100% {
transform: scaleX(var(--s,1)) rotate(360deg);
}
}
}

@ -0,0 +1,6 @@
import css from './index.module.scss'
export default function One(){
return <div className={css.One}>
<div className={[css.loader, css["loader_bubble"]].join(' ')}></div>
</div>
}

@ -0,0 +1,51 @@
.One{
position: relative;
height: 200px;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
.loader {
position: relative;
display: block;
width: 44px;
height: 44px;
font-size: 15px;
box-shadow: 9px 9px 33px #d1d1d1, -9px -9px 33px #ffffff;
}
.loader::before,
.loader::after {
content: '';
position: absolute;
display: block;
}
.loader_bubble::before {
top: 10px;
left: 10px;
width: 10px;
height: 10px;
background: #fff;
border-radius: 50%;
}
.loader_bubble {
background: linear-gradient(180deg, rgb(0, 91, 228) 10%, rgb(75, 127, 240) 100%);
border-radius: 50%;
transform-origin: 50% 50%;
animation: bubble7234 1200ms cubic-bezier(0.645, 0.045, 0.355, 1) infinite;
}
@keyframes bubble7234 {
0% {
transform: translate3d(0,0,0) rotate(0);
}
100% {
transform: translate3d(0,0,0) rotate(360deg);
}
}
}

@ -0,0 +1,15 @@
import css from './index.module.scss'
export default function Pacman(){
return <div className={css.Pacman}>
<div className={css["loader-wrapper"]}>
<div className={css.packman}></div>
<div className={css.dots}>
<div className={css.dot}></div>
<div className={css.dot}></div>
<div className={css.dot}></div>
<div className={css.dot}></div>
</div>
</div>
</div>
}

@ -0,0 +1,123 @@
.Pacman{
position: relative;
height: 200px;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #333333;
.loader-wrapper {
position: relative;
//top: 0;
//left: 0;
//bottom: 0;
//right: 0;
//margin: auto;
}
.loader-wrapper .packman::before {
content: '';
position: absolute;
width: 50px;
height: 25px;
background-color: #EFF107;
border-radius: 100px 100px 0 0;
transform: translate(-50%, -50%);
animation: pac-top 0.5s linear infinite;
transform-origin: center bottom;
}
.loader-wrapper .packman::after {
content: '';
position: absolute;
width: 50px;
height: 25px;
background-color: #EFF107;
border-radius: 0 0 100px 100px;
transform: translate(-50%, 50%);
animation: pac-bot 0.5s linear infinite;
transform-origin: center top;
}
@keyframes pac-top {
0% {
transform: translate(-50%, -50%) rotate(0)
}
50% {
transform: translate(-50%, -50%) rotate(-30deg)
}
100% {
transform: translate(-50%, -50%) rotate(0)
}
}
@keyframes pac-bot {
0% {
transform: translate(-50%, 50%) rotate(0)
}
50% {
transform: translate(-50%, 50%) rotate(30deg)
}
100% {
transform: translate(-50%, 50%) rotate(0)
}
}
.dot {
position: absolute;
z-index: -1;
top: 8px;
width: 10px;
height: 10px;
border-radius: 50%;
background: #fff;
}
.dots .dot:nth-child(1) {
left: 90px;
animation: dot-stage1 0.5s infinite;
}
.dots .dot:nth-child(2) {
left: 60px;
animation: dot-stage1 0.5s infinite;
}
.dots .dot:nth-child(3) {
left: 30px;
animation: dot-stage1 0.5s infinite;
}
.dots .dot:nth-child(4) {
left: 10px;
animation: dot-stage2 0.5s infinite;
}
@keyframes dot-stage1 {
0% {
transform: translate(0, 0);
}
100% {
transform: translate(-24px, 0);
}
}
@keyframes dot-stage2 {
0% {
transform: scale(1);
}
5%, 100% {
transform: scale(0);
}
}
}

@ -0,0 +1,9 @@
import css from './index.module.scss'
export default function TableTennis(){
return <div className={css.TableTennis}>
<div className={css.bar}>
<div className={css.ball}></div>
</div>
</div>
}

@ -0,0 +1,65 @@
.TableTennis{
position: relative;
height: 200px;
width: 100%;
background: #333;
}
$up-down6123 : up-down6123;
$ball-move8234: ball-move8234;
.ball {
position: relative;
bottom: 50px;
left: calc(100% - 20px);
width: 50px;
height: 50px;
background: #fff;
border-radius: 50%;
animation: $ball-move8234 3s ease-in-out 1s infinite alternate;
}
.ball::after {
position: absolute;
content: '';
top: 25px;
right: 5px;
width: 5px;
height: 5px;
background: #000;
border-radius: 50%;
}
.bar {
position: relative;
top:100px;
width: 200px;
height: 12.5px;
background: #FFDAAF;
border-radius: 30px;
transform: rotate(-15deg);
animation: $up-down6123 3s ease-in-out 1s infinite alternate;
}
@keyframes up-down6123 {
from {
transform: rotate(-15deg);
}
to {
transform: rotate(15deg);
}
}
@keyframes ball-move8234 {
from {
left: calc(100% - 40px);
transform: rotate(360deg);
}
to {
left: calc(0% - 20px);
transform: rotate(0deg);
}
}

@ -0,0 +1,7 @@
import css from './index.module.scss'
export default function Three(){
return <div className={css.Three}>
<div className={css.loader}></div>
</div>
}

@ -0,0 +1,34 @@
.Three{
position: relative;
height: 200px;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
background: #111;
.loader {
width: 60px;
aspect-ratio: 2;
--_g: no-repeat radial-gradient(circle closest-side, #fff 90%, #fff0);
background: var(--_g) 0% 50%, var(--_g) 50% 50%, var(--_g) 100% 50%;
background-size: calc(100% / 3) 50%;
animation: l3 1s infinite linear;
}
@keyframes l3 {
20% {
background-position: 0% 0%, 50% 50%, 100% 50%;
}
40% {
background-position: 0% 100%, 50% 0%, 100% 50%;
}
60% {
background-position: 0% 50%, 50% 100%, 100% 0%;
}
80% {
background-position: 0% 50%, 50% 50%, 100% 100%;
}
}
}

@ -0,0 +1,8 @@
import css from './index.module.scss'
export default function Two(){
return <div className={css.Two}>
<div className={css["chaotic-orbit"]}></div>
</div>
}

@ -0,0 +1,163 @@
.Two{
position: relative;
height: 200px;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
.chaotic-orbit {
--uib-size: 25px;
--uib-speed: 1.5s;
--uib-color: black;
position: relative;
display: flex;
align-items: center;
justify-content: center;
height: var(--uib-size);
width: var(--uib-size);
animation: rotate936 calc(var(--uib-speed) * 1.667) infinite linear;
}
.chaotic-orbit::before,
.chaotic-orbit::after {
content: '';
position: absolute;
height: 60%;
width: 60%;
border-radius: 50%;
background-color: var(--uib-color);
will-change: transform;
flex-shrink: 0;
}
.chaotic-orbit::before {
animation: orbit var(--uib-speed) linear infinite;
}
.chaotic-orbit::after {
animation: orbit var(--uib-speed) linear calc(var(--uib-speed) / -2)
infinite;
}
@keyframes rotate936 {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes orbit {
0% {
transform: translate(calc(var(--uib-size) * 0.5)) scale(0.73684);
opacity: 0.65;
}
5% {
transform: translate(calc(var(--uib-size) * 0.4)) scale(0.684208);
opacity: 0.58;
}
10% {
transform: translate(calc(var(--uib-size) * 0.3)) scale(0.631576);
opacity: 0.51;
}
15% {
transform: translate(calc(var(--uib-size) * 0.2)) scale(0.578944);
opacity: 0.44;
}
20% {
transform: translate(calc(var(--uib-size) * 0.1)) scale(0.526312);
opacity: 0.37;
}
25% {
transform: translate(0%) scale(0.47368);
opacity: 0.3;
}
30% {
transform: translate(calc(var(--uib-size) * -0.1)) scale(0.526312);
opacity: 0.37;
}
35% {
transform: translate(calc(var(--uib-size) * -0.2)) scale(0.578944);
opacity: 0.44;
}
40% {
transform: translate(calc(var(--uib-size) * -0.3)) scale(0.631576);
opacity: 0.51;
}
45% {
transform: translate(calc(var(--uib-size) * -0.4)) scale(0.684208);
opacity: 0.58;
}
50% {
transform: translate(calc(var(--uib-size) * -0.5)) scale(0.73684);
opacity: 0.65;
}
55% {
transform: translate(calc(var(--uib-size) * -0.4)) scale(0.789472);
opacity: 0.72;
}
60% {
transform: translate(calc(var(--uib-size) * -0.3)) scale(0.842104);
opacity: 0.79;
}
65% {
transform: translate(calc(var(--uib-size) * -0.2)) scale(0.894736);
opacity: 0.86;
}
70% {
transform: translate(calc(var(--uib-size) * -0.1)) scale(0.947368);
opacity: 0.93;
}
75% {
transform: translate(0%) scale(1);
opacity: 1;
}
80% {
transform: translate(calc(var(--uib-size) * 0.1)) scale(0.947368);
opacity: 0.93;
}
85% {
transform: translate(calc(var(--uib-size) * 0.2)) scale(0.894736);
opacity: 0.86;
}
90% {
transform: translate(calc(var(--uib-size) * 0.3)) scale(0.842104);
opacity: 0.79;
}
95% {
transform: translate(calc(var(--uib-size) * 0.4)) scale(0.789472);
opacity: 0.72;
}
100% {
transform: translate(calc(var(--uib-size) * 0.5)) scale(0.73684);
opacity: 0.65;
}
}
}

@ -0,0 +1,18 @@
import React from "react";
const TableTennis = React.lazy(() => import('@components/HtmlLoading/TableTennis'))
const Pacman = React.lazy(() => import("@components/HtmlLoading/Pacman/index.jsx"))
const Eye = React.lazy(() => import("@components/HtmlLoading/Eye/index.jsx"))
const One = React.lazy(() => import("@components/HtmlLoading/One/index.jsx"))
const Two = React.lazy(() => import("@components/HtmlLoading/Two/index.jsx"))
const Three = React.lazy(() => import("@components/HtmlLoading/Three/index.jsx"))
export default function HtmlLoading(){
return <div>
<TableTennis/>
<Pacman/>
<Eye/>
<One/>
<Two/>
<Three/>
</div>
}

@ -0,0 +1,45 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import {BrowserRouter} from "react-router-dom";
import PrivateRoute from "@routes/PrivateRoute.jsx";
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<BrowserRouter>
<PrivateRoute>
<App />
</PrivateRoute>
</BrowserRouter>
</React.StrictMode>,
)
window.onload = loading
function loading(){
const nowTime = new Date().getTime()
console.log('staring...');
const passTime = nowTime - window.startime;
console.log(window.location.pathname == '/')
if(window.location.pathname == '/' && passTime < 500){
setTimeout(() => {
startLoad()
}, 550 - passTime)
}else{
startLoad()
}
}
function startLoad(){
const loader = document.querySelector('#loading');
const upFace = document.querySelector('#upFace');
const downFace = document.querySelector('#downFace');
const root = document.querySelector('#root');
const loaderBox = document.querySelector('#loaderBox');
upFace.classList.add('upOpen')
downFace.classList.add('downOpen')
root.classList.add('openRoot')
loaderBox.classList.add('hideLoader')
setTimeout(() => {
loader.remove()
}, 1500)
}

@ -0,0 +1,18 @@
import {useEffect} from "react";
import { useLocation, useParams, useNavigate } from 'react-router-dom';
export default function PrivateRoute(props){
const location = useLocation();
const params = useParams();
const navigate = useNavigate()
useEffect(() => {
// console.log(location.pathname); //
// console.log(location.search); //
// console.log(location.hash); // URL
// console.log(params); // URL "id"
if(location.pathname == '/test'){
navigate('/')
}
}, [0]);
return props.children
}

@ -0,0 +1,37 @@
// | ------------------------------------------------------------
// | @: version 0.1
// | @: Nie-x7129
// | @E-mail: x71291@outlook.com
// | @: react-template
// | @: index.jsx -
// | @: 2023-11-26 16:05
// | @: 2023-11-26 16:05
// | @:
// | -*-*-*- (----) -*-*-*-
// | =
// | ------------------------------------------------------------
import { Navigate } from 'react-router-dom'
import React from "react";
const Test = React.lazy(() => import("@views/Test/index.jsx"))
const HtmlLoading = React.lazy(() => import("@components/HtmlLoading/index.jsx"))
const routes = [
{
path: '/about',
element: <HtmlLoading />
}, {
path: '/home',
element: <Test />
}, /*{
path: '/',
element: <Navigate to='/about' />
}*/, {
path: '/',
element: <Test/>
}
]
export default routes

@ -0,0 +1,23 @@
// | ------------------------------------------------------------
// | @版本: version 0.1
// | @创建人: 【Nie-x7129】
// | @E-mail: x71291@outlook.com
// | @所在项目: react-template
// | @文件描述: index.js -
// | @创建时间: 2023-11-26 16:47
// | @更新时间: 2023-11-26 16:47
// | @修改记录:
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
// | =
// | ------------------------------------------------------------
import { configureStore } from '@reduxjs/toolkit';
import DefaultSlice from "@/store/slice/defaultSlice.js";
const store = configureStore({
reducer: {
defaultSlice: DefaultSlice,
},
});
export default store;

@ -0,0 +1,63 @@
// | ------------------------------------------------------------
// | @版本: version 0.1
// | @创建人: 【Nie-x7129】
// | @E-mail: x71291@outlook.com
// | @所在项目: react-template
// | @文件描述: defaultSlice.js -
// | @创建时间: 2023-11-26 17:20
// | @更新时间: 2023-11-26 17:20
// | @修改记录:
// | -*-*-*- (时间--修改人--修改说明) -*-*-*-
// | =
// | ------------------------------------------------------------
import {createAsyncThunk, createSlice} from '@reduxjs/toolkit';
export const decremented = createAsyncThunk(
'user/fetchData',
async (data, thunkAPI) => {
// 调用API
console.log(data, thunkAPI)
await new Promise(res => {
setTimeout(() =>{
res()
}, 1000)
})
return; // 或根据你的API返回结构进行调整
}
);
export const defaultSlice = createSlice({
name: 'defaultSlice',
initialState: {
value: 0,
},
reducers: {
incremented: (state,b) => {
state.value += 1;
},
},
extraReducers: {
// 当 fetchUserData action 被派发时,根据 action 的不同状态对 state 进行更新
[decremented.pending]: (state, action) => {
// state.isLoading = true;
// state.error = null;
},
[decremented.fulfilled]: (state, action) => {
// state.isLoading = false;
// state.data = action.payload; // 假设我们的API返回了用户的数据结构
state.value -= 1;
},
[decremented.rejected]: (state, action) => {
// state.isLoading = false;
// state.error = action.error.message;
},
},
});
export const { incremented } = defaultSlice.actions;
export default defaultSlice.reducer;

@ -0,0 +1,24 @@
import {useEffect, useState} from "react";
import store from "@/store/index.js";
import {incremented, decremented} from "@/store/slice/defaultSlice.js";
export default function Test(){
const [count, setCount] = useState(store.getState().defaultSlice.value);
useEffect(() => {
console.log(store.getState())
const unsubscribe = store.subscribe(() => {
setCount(store.getState().defaultSlice.value);
});
return unsubscribe; //
}, []);
return <div>
<h1>{count}</h1>
<button onClick={() => store.dispatch(incremented())}>Increment</button>
<button onClick={() => store.dispatch(decremented(1))}>Decrement</button>
</div>
}

@ -0,0 +1 @@
https://blog.csdn.net/qq_30769437/article/details/128149273

@ -0,0 +1,314 @@
如果你需要创建一个Redux应用,但不想使用react-redux和`createStore`(这通常是Redux的标准API用于创建store的方法),你可以使用Redux Toolkit中的`configureStore`作为`createStore`的替代方案来创建store。
Redux Toolkit 是官方推荐的方式来设置store,它提供了更简化的API和一些有用的工具,比如默认集成了redux-thunk中间件以及Redux DevTools扩展支持。下面是一个不使用react-redux的示例,但是如果你想完全不使用任何辅助工具或库,仅使用最基本的Redux API(这是不推荐的,因为你会失去许多便利和性能优化),那你将需要自己管理store的状态订阅和更新组件的渲染。
下面是一个不使用`createStore`和`react-redux`的Redux应用例子:
目录结构:
```
my-app/
src/
store/
index.js // 创建和配置应用程序的Redux store
counterReducer.js // 管理计数状态的reducer
components/
Counter.js // 一个使用Redux store的React组件
App.js // 应用程序的根组件
index.js // 应用程序的主入口文件
```
`store/index.js`:
```javascript
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterReducer';
const store = configureStore({
reducer: {
counter: counterReducer,
},
});
export default store;
```
`store/counterReducer.js`:
```javascript
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const initialState = {
value: 0,
};
function counterReducer(state = initialState, action) {
switch (action.type) {
case INCREMENT:
return { ...state, value: state.value + 1 };
case DECREMENT:
return { ...state, value: state.value - 1 };
default:
return state;
}
}
export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });
export default counterReducer;
```
`components/Counter.js`:
```jsx
import React, { useState, useEffect } from 'react';
import store from '../store';
import { increment, decrement } from '../store/counterReducer';
export const Counter = () => {
const [count, setCount] = useState(store.getState().counter.value);
useEffect(() => {
const unsubscribe = store.subscribe(() => {
setCount(store.getState().counter.value);
});
return unsubscribe; // 在组件卸载时取消订阅
}, []);
return (
<div>
<h1>{count}</h1>
<button onClick={() => store.dispatch(increment())}>Increment</button>
<button onClick={() => store.dispatch(decrement())}>Decrement</button>
</div>
);
};
```
`App.js`:
```jsx
import React from 'react';
import { Counter } from './components/Counter';
const App = () => {
return (
<div>
<Counter />
</div>
);
}
export default App;
```
`index.js`:
```jsx
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import store from './store';
import { increment } from './store/counterReducer';
// 可以在这里测试我们的Redux store是否正常工作
console.log(store.getState()); // 应该看到初始状态
store.dispatch(increment());
console.log(store.getState()); // 状态应该更新,并增加了1
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
```
在上述的示例中,我们使用`useEffect`来订阅Redux store和清理订阅,通过store的`getState`方法获取当前的状态,并通过`dispatch`方法来派发actions。这种方式下,我们没有使用react-redux,而是手动连接到Redux store并监听状态变化。
请注意,这样手动处理Redux可能会使你的应用程序难以管理和扩展,特别是在大型应用程序中,react-redux提供的`Provider`和`connect`方法或者hooks`useSelector`和`useDispatch`可以更好地帮助你管理连接逻辑和组件更新,提高应用的性能。
在 Redux Toolkit 中,`createSlice` 通常用于同步更新 state ,但当它与 `createAsyncThunk` 一起使用时,可以非常容易地用于异步更新。`createAsyncThunk` 会生成三种 action 类型(pending,fulfilled,rejected),你可以在 `createSlice``extraReducers` 属性中监听这些 action:
```javascript
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { userAPI } from './userAPI';
// 首先创建一个异步 thunk action
export const fetchUserData = createAsyncThunk(
'user/fetchData',
async (userId, thunkAPI) => {
// 调用API
const response = await userAPI.fetchById(userId);
return response.data; // 或根据你的API返回结构进行调整
}
);
// 然后创建 slice,这里我们可以处理我们上面定义的三种状态的actions
const userSlice = createSlice({
name: 'user',
initialState: {
data: null,
isLoading: false,
error: null,
},
reducers: {
// 你的其他同步 reducers 可以在这里定义
},
extraReducers: {
// 当 fetchUserData action 被派发时,根据 action 的不同状态对 state 进行更新
[fetchUserData.pending]: (state, action) => {
state.isLoading = true;
state.error = null;
},
[fetchUserData.fulfilled]: (state, action) => {
state.isLoading = false;
state.data = action.payload; // 假设我们的API返回了用户的数据结构
},
[fetchUserData.rejected]: (state, action) => {
state.isLoading = false;
state.error = action.error.message;
},
},
});
export const { actions, reducer } = userSlice;
```
在这个例子中:
- `fetchUserData.pending` 相关的 reducer 将在请求开始时将 `isLoading` 状态设置为 true。
- `fetchUserData.fulfilled` 相关的 reducer 将在请求成功并收到数据时更新 `data` ,并将 `isLoading` 设置为 false。
- `fetchUserData.rejected` 相关的 reducer 将在请求失败时设置错误信息,并将 `isLoading` 设置为 false。
通过使用 `createAsyncThunk``createSlice``extraReducers` ,我们也很方便的可以将异步行为整合到我们的 Redux state 管理中。
在视图(常常指的是 React 组件)中使用 `@reduxjs/toolkit``createAsyncThunk` 创建的异步 action 通常涉及以下几个步骤:
1. 将 Redux store 和 React 组件连接起来,可以使用 `react-redux` 提供的 `useSelector` 来选择 state,以及 `useDispatch` 来派发 actions。
2. 创建视图(UI组件),并在适当的时候(如组件挂载或者用户互动事件)派发异步 action。
3. 显示加载状态、错误信息或者成功得到的数据。
下面是一个例子,展示了如何在一个 React 组件中使用异步 action:
```jsx
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchUserData } from './userSlice';
// 以上的 userSlice 是我们之前定义的包含 fetchUserData 异步 action 的文件
function UserComponent({ userId }) {
const dispatch = useDispatch();
// 从 Redux state 中选择数据
const user = useSelector(state => state.user.data);
const isLoading = useSelector(state => state.user.isLoading);
const error = useSelector(state => state.user.error);
// 当组件挂载时,派发 fetchUserData action
useEffect(() => {
dispatch(fetchUserData(userId));
}, [userId, dispatch]);
// 根据 state 渲染 UI
if (isLoading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
return (
<div>
<h1>User Data</h1>
{/* 假设 user 对象有 name 属性 */}
{user ? <p>Name: {user.name}</p> : <p>No user details</p>}
</div>
);
}
export default UserComponent;
```
在这个 React 组件中:
- 使用 `useDispatch` hook 获取 `dispatch` 方法,以便于我们可以派发 actions。
- 使用 `useSelector` hook 从 Redux store 中选择 `user.state` 中的各部分数据。
- 使用 `useEffect` React hook 来触发 `fetchUserData` 异步 action。当 `userId` 改变或者组件首次渲染时会重新触发。
- 在 UI 中根据 `isLoading`, `error`, 和 `user` 状态显示不同的内容。如果 `isLoading` 为 true,显示加载状态;如果 `error` 存在,则显示错误;否则显示用户信息。
`createAsyncThunk` 中使用的 `thunkAPI` 对象是由 Redux Thunk 提供的一个参数,包含了几个有用的属性和方法,使得在 thunk 中可以执行更为复杂的逻辑。`thunkAPI` 在每次调用异步 thunk 函数时都会被提供,并且具有以下字段和方法:
1. **dispatch**: 允许你在 thunk 中派发 action。
2. **getState**: 允许你访问当前的 Redux store state。
3. **extra**: 如果在创建 Redux store 的 `configureStore` 方法中定义了 `extraArgument`,则这里可以取得。
4. **requestId**: 是对每次异步 thunk action 调用的唯一标识。
5. **signal**: 是一个 `AbortSignal` 对象,与本次异步操作相关联,可以用来响应取消操作。
6. **rejectWithValue**: 一个函数,允许你在发生错误时手动地派发一个拒绝 (rejected) action,并携带自定义的 payload 值。
7. **fulfillWithValue**: 当你需要在 resolve (解决) action 中提供一个不同于异步操作返回结果的 payload 时,可以用这个函数。
8. **rejectWithReason**: 类似 `rejectWithValue`,允许在 rejected action 中提供自定义拒绝原因,更明确地说明拒绝的原因。
这些功能给予开发者很大的灵活性去处理异步逻辑和实现复杂的异步操作流程。例如,使用 `dispatch` 来派发其他 actions,利用 `getState` 获取最新的 state 来指导后续逻辑,或使用 `rejectWithValue` 在出错时捕捉错误并优化错误处理。
以下是一个使用 `thunkAPI` 的例子:
```javascript
export const fetchUserData = createAsyncThunk(
'user/fetchData',
async (userId, thunkAPI) => {
try {
const response = await userAPI.fetchById(userId);
return response.data;
} catch (error) {
// 如果 API 抛出一个错误,我们可以选择发送一个拒绝action,并附带一个自定义的payload
return thunkAPI.rejectWithValue({errorMessage: 'Cannot load user data'});
}
}
);
```
在这个例子中,如果 `userAPI.fetchById` 方法抛出一个错误,`thunkAPI.rejectWithValue` 方法则被用来派发一个拒绝的 action,并附上一个含错误信息的 payload。这使得 reducer 可以捕捉这个拒绝的 action,并根据附带的 payload 更新 state。

@ -0,0 +1,17 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
'@views':path.resolve(__dirname, './src/views'),
'@components': path.resolve(__dirname, './src/components'),
'@utils': path.resolve(__dirname, './src/utils'),
'@routes': path.resolve(__dirname, './src/routes')
},
},
})
Loading…
Cancel
Save