react-store:react hooks 结合 context api 实现 redux 的数据管理功能

@cpage/react-store

@cpage/react-store 是基于 react hooks 和 context api 实现的类似的 redux 的数据管理库。支持数据存储,方法调用,可以在 class 组件和 function 组件中使用,支持同步和异步的方法调用。

GitHub 仓库地址

api 介绍

api 作用 适合场景
StoreProvider 全局用的 provider app.js 或者单个模块的根文件
StoreContext 存储用的 Context function 组件和 class 组件均适用
useStoreHook store 钩子函数,包含state和dispatch function 组件
useStateHook 获取 state 用的 hook function 组件
useDispatchHook 进行事件派发的 hook function 组件
connect 添加属性和方法到组件中 function/class 组件

备注:

    • 0
      点赞
    • 0
      收藏
      觉得还不错? 一键收藏
    • 0
      评论
    React Hooks 是一种 React 新特性,可以让函数组件具有类组件的功能,包括状态管理。而 Redux 则是一种全局状态管理工具,用于管理整个应用的状态。 要将数据存入 Redux,你需要使用 ReduxAPI,包括 createStore、combineReducers、dispatch 等来创建和管理 store,然后使用 useSelector 和 useDispatch Hooks 来获取和更新 store 中的数据。 下面是一个示例: 1. 创建 Redux store ```javascript import { createStore } from 'redux'; // 定义 reducer const counterReducer = (state = { count: 0 }, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: return state; } }; // 创建 store const store = createStore(counterReducer); ``` 2. 在组件中使用 useSelector 和 useDispatch Hooks ```javascript import { useSelector, useDispatch } from 'react-redux'; const Counter = () => { const count = useSelector(state => state.count); const dispatch = useDispatch(); const handleIncrement = () => { dispatch({ type: 'INCREMENT' }); }; const handleDecrement = () => { dispatch({ type: 'DECREMENT' }); }; return ( <div> <h1>Count: {count}</h1> <button onClick={handleIncrement}>+</button> <button onClick={handleDecrement}>-</button> </div> ); }; ``` 在上面的代码中,我们使用 useSelector Hook 获取 store 中的 count 数据,并使用 useDispatch Hook 获取 dispatch 函数,以便更新 store 中的数据。 当点击按钮时,我们分别调用 handleIncrement 和 handleDecrement 函数来分发 INCREMENT 和 DECREMENT action,从而更新 store 中的 count 数据。

    “相关推荐”对你有帮助么?

    • 非常没帮助
    • 没帮助
    • 一般
    • 有帮助
    • 非常有帮助
    提交
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值