0.0.10 • Published 1 year ago

@rasir/jotai-redux v0.0.10

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

@rasir/jotai-redux

封装 jotai 模拟 redux-saga 的 api

使用方法

// APIs
import {
  select,
  useSelector,
  useUpdateStore,
  useDispatch,
  createStore,
  updateState,
  getStore,
  addStores,
  dispatch,
} from "@rasir/jotai-redux";
    1. createStore 用于初始化 store
const store = createStore({
  states: {
    user: { id: 1, name: "rasir" },
  },
  actions: {
    user: {
      update:async ({type:"user/update",payload},{select,put,update,all}) => {
        const {id} = select(({user}) => user);
        if(id === payload.id){
         await all([
            put({type:"user/updateName",payload:payload.name}),
            put({type:'user/updateId',payload:payload.id})
          ])
        }
      },
      updateName:async ({type:"user/updateName",payload},{select,put,update,all}) => {
        await update('user',{name:payload});
      },
       updateId:async ({type:"user/updateId",payload},{select,put,update,all}) => {
         await update('user',{id:payload});
      },
    },
  },
});
    1. addStores 用于添加 store。参数与createStore相同,不同点在于,addStores 会合并到已有的 store
addStores({
  states: { todo: { id: 1, name: "todo1" } },
  actions: { todo: { update: () => {} } },
});
    1. updateState 用于更新 store 中某个 state
updateState("user", { name: "rasir2" });
    1. getStore 用于获取 store 中所有的 state
const store = getStore();
    1. useSelector 用于获取 store
const user = useSelector(({ user }) => user);
    1. useUpdateStore 用于更新 store
const update = useUpdateStore("user");
update({ name: "rasir2" });
    1. select 用于获取 store
const user = useSelector(({ user }) => user);
    1. useDispatch 用于获取 dispatch
const dispatch = useDispatch();
dispatch({ type: "user/update", payload: { id: 2, name: "rasir2" } });
    1. dispatch 用于获取触发 action 的方法
dispatch({ type: "user/update", payload: { id: 2, name: "rasir2" } });
    1. 高阶组件(HOC)connect 类似于 react-redux 的 connect,用于将 store 中的 state 和 dispatch 与组件进行绑定
const App = ({ name, update }) => {
  return (
    <button onClick={() => update({ id: 1, name: "rasir2" })}>{name}</button>
  );
};
export default connect(
  ({ user: { name } }) => ({ name }),
  (dispatch) => ({
    update: (payload) => dispatch({ type: "user/update", payload }),
  })
)(App);

jotai 原有 api 均可直接使用

0.0.10

1 year ago

0.0.9

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago