在一页纸上从头理解 React Redux

2025-06-08

在一页纸上从头理解 React Redux

Redux 是一个流行的 React 和 React Native 状态管理库。
以下是 Redux 的所有组件,包含在一个页面中。

npx create-react-app reactapp
Enter fullscreen mode Exit fullscreen mode

cd reactapp

yarn add react-redux
Enter fullscreen mode Exit fullscreen mode

在 index.js 中添加此内容

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { createStore } from "redux";
import allReducer from "./reducers";

//ACTION  -> INCREMENT (describes what you want to do!) it's a simple function

const increment = () => {
    return {
        type: "INCREMENT",
    };
};

const decrement = () => {
    return {
        type: "DECREMENT",
    };
};

//REDUCER -> (action transfer from one state to another state, it gonna modify our store)
//You can have many reducers (Auth reducer, Movielist reducer etc ...)
const counter = (state = 0, action) => {
    switch (action.type) {
        case "INCREMENT":
            return state + 1;
        case "DECREMENT":
            return state - 1;
    }
};

//STORE  -> Globalized STATE
let store = createStore(counter);

//Display it in the console.
store.subscribe(() => console.log(store.getState()));

//DISPATCH (DISPATTCH this action to the reducer)
store.dispatch(increment());
store.dispatch(decrement());
store.dispatch(increment());

ReactDOM.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>,
    document.getElementById("root")
);

reportWebVitals();

Enter fullscreen mode Exit fullscreen mode

测试它:检查控制台以查看它如何增加和减少。

Github Repo有关更高级的方法:
https://github.com/Byusa/learn-redux

这个 repo 展示了 redux 的使用,它可以是一种适当的方式,使用 store 和多个 reducer 自己的文件夹。

参考:
https://www.youtube.com/watch?v =CVpUuw9XSjY

鏂囩珷鏉ユ簮锛�https://dev.to/byusa/understand-react-redux-from-scrach-on-one-page-340g
PREV
⚙️ 使用 Prettier、AirBnB Styleguide、Husky 和 ​​lint-staged 将 Angular 应用迁移到 ESLint
NEXT
适用于 Vue 或 React 的 Electron 入门代码生成器 Elecrue 是什么?如何安装 Elecure?如何使用?常见问题解答