Hogan |軟體工程師隨筆
成大電機畢業,現職外商產品工程師,我的工作內容 與全端軟體開發和手機app開發相關。主要分享一些程式碼、軟體教學、經驗交流。IG : hogan.tech
import create from 'zustand'const useBearStore = create((set) => ({bears: 0,increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),removeAllBears: () => set({ bears: 0 }),}))
function BearCounter() {const bears = useBearStore((state) => state.bears)return <h1>{bears} around here ...</h1>}function Controls() {const increasePopulation = useBearStore((state) => state.increasePopulation)return <button onClick={increasePopulation}>one up</button>}
import create from "zustand"type Product = { sku: string; name: string; image: string }type CartState = {products: Product[]cart: { [sku: string]: number }addToCart: (sku: string) => voidremoveFromCart: (sku: string) => void}// Selectors// ...// Initialize our store with initial values and actions to mutate the stateexport const useCart = create<CartState>(set => ({products: [// ...],cart: {},// Actions// ...}))
import { createSlice, configureStore, PayloadAction } from "@reduxjs/toolkit"import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux"// Slices// Definee the shape of the state and how to mutate ittype ICart = { [sku: string]: number }const cartInitialState: ICart = {}const cartSlice = createSlice({name: "cart",initialState: cartInitialState,reducers: {// ...},})type IProduct = { sku: string; name: string; image: string }const productsInitialState: IProduct[] = [// ...]const productsSlice = createSlice({name: "products",initialState: productsInitialState,reducers: {},})// Actions// ...// Selectors// ...// Storeexport const store = configureStore({reducer: {cart: cartSlice.reducer,products: productsSlice.reducer,},})// ...const App = () => {return (<Provider store={store}><NavigationContainer><Stack.Navigator>{/* ... */}</Stack.Navigator><StatusBar style="auto" /></NavigationContainer></Provider>)}
import { types, Instance } from "mobx-state-tree"const Product = types.model({sku: types.string,name: types.string,image: types.string,})// Model and type our data with mobx state treeconst CartStore = types.model("CartStore", {products: types.array(Product),cart: types.map(types.number),})// Actions to mutate the state.actions(store => ({// ...}))// Views are like selectors.views(self => ({// ...}))type CartStoreType = Instance<typeof CartStore>// Spin up a hook to use our store and provide initial values to itlet _cartStore: CartStoreTypeexport const useCart = () => {if (!_cartStore) {_cartStore = CartStore.create({products: [// ...],cart: {},})}return _cartStore}