react的简单版redux:

// 导入必要的依赖
import React from 'react';
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';

// 定义初始状态
const initialState = {
    count: 0
};

// 定义 reducer 函数
const countReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return { ...state, count: state.count + 1 };
        case 'DECREMENT':
            return { ...state, count: state.count - 1 };
        default:
            return state;
    }
};

// 创建 Redux store
const store = createStore(countReducer);

// 定义一个组件来展示状态和派发 actions
const Counter = () => {
    const count = useSelector(state => state.count);
    const dispatch = useDispatch();

    const increment = () => {
        dispatch({ type: 'INCREMENT' });
    };

    const decrement = () => {
        dispatch({ type: 'DECREMENT' });
    };

    return (
        

Count: {count}

); }; // 使用 Provider 组件将 Redux store 绑定到根组件 const App = () => { return ( ); }; export default App;

你可能感兴趣的:(react.js,javascript,前端)