@rasir/jotai-redux
v0.0.10
Published
封装jotai模拟redux-saga的api
Downloads
1
Readme
@rasir/jotai-redux
封装 jotai 模拟 redux-saga 的 api
使用方法
// APIs
import {
select,
useSelector,
useUpdateStore,
useDispatch,
createStore,
updateState,
getStore,
addStores,
dispatch,
} from "@rasir/jotai-redux";
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});
},
},
},
});
addStores
用于添加 store。参数与createStore
相同,不同点在于,addStores
会合并到已有的 store
addStores({
states: { todo: { id: 1, name: "todo1" } },
actions: { todo: { update: () => {} } },
});
updateState
用于更新 store 中某个 state
updateState("user", { name: "rasir2" });
getStore
用于获取 store 中所有的 state
const store = getStore();
useSelector
用于获取 store
const user = useSelector(({ user }) => user);
useUpdateStore
用于更新 store
const update = useUpdateStore("user");
update({ name: "rasir2" });
select
用于获取 store
const user = useSelector(({ user }) => user);
useDispatch
用于获取 dispatch
const dispatch = useDispatch();
dispatch({ type: "user/update", payload: { id: 2, name: "rasir2" } });
dispatch
用于获取触发 action 的方法
dispatch({ type: "user/update", payload: { id: 2, name: "rasir2" } });
- 高阶组件(HOC)
connect
类似于 react-redux 的 connect,用于将 store 中的 state 和 dispatch 与组件进行绑定
- 高阶组件(HOC)
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);