在 React 中,可以使用 React Context 和 useReducer 来实现类似于 Pinia 的本地存储方式。下面是一个简单的示例代码:

import React, { createContext, useReducer } from 'react';

// 创建一个存储上下文
const StoreContext = createContext();

// 定义存储的初始状态和操作
const initialState = {
  count: 0,
};

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { ...state, count: state.count + 1 };
    case 'decrement':
      return { ...state, count: state.count - 1 };
    default:
      throw new Error('Unsupported action type');
  }
}

// 创建存储提供器组件
function StoreProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <StoreContext.Provider value={{ state, dispatch }}>
      {children}
    </StoreContext.Provider>
  );
}

// 在组件中使用存储
function Counter() {
  const { state, dispatch } = useContext(StoreContext);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  );
}

// 在应用中使用存储提供器
function App() {
  return (
    <StoreProvider>
      <Counter />
    </StoreProvider>
  );
}

 export default App;

在上面的示例中,我们创建了一个存储提供器组件StoreProvider,它使用useReducer来管理存储的状态和操作。然后,我们使用React Context来在组件树中传递存储的上下文。

Counter组件中,我们使用useContext来获取存储的状态和操作,然后根据需要更新状态。

最后,在应用的根组件App中,我们将Counter组件包装在StoreProvider中,以便在整个应用中使用存储。

React 本地存储实现:类似 Pinia 的 Context 和 useReducer 示例

原文地址: https://www.cveoy.top/t/topic/qvW8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录