Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. import React, { createContext, useReducer, useContext } from 'react';
  2. import PropTypes from 'prop-types';
  3. import en_US from 'antd/lib/locale-provider/en_US';
  4. import zh_TW from 'antd/lib/locale-provider/zh_TW';
  5. import zh_CN from 'antd/lib/locale-provider/zh_CN';
  6.  
  7. import { userInitialState, userActions } from './user';
  8.  
  9. const locales = {
  10. en_US,
  11. zh_TW,
  12. zh_CN
  13. }
  14.  
  15. const getAntdLocale = (lang) => {
  16. var locale = locales.en_US;
  17. if(lang==='zh_Hant') locale = locales.zh_TW;
  18. if(lang==='zh_Hans') locale = locales.zh_CN;
  19. return locale;
  20. }
  21.  
  22. const initialState = {
  23. lang: localStorage.getItem('lang') || 'en',
  24. antdLocale: getAntdLocale(localStorage.getItem('lang')||'en_US'),
  25. ...userInitialState
  26. };
  27.  
  28. const StoreContext = createContext(initialState);
  29.  
  30. const Actions = {
  31. changeLang: (state, lang) => {
  32. localStorage.setItem('lang', lang);
  33. return {lang, antdLocale: getAntdLocale(lang)};
  34. },
  35. ...userActions
  36. };
  37.  
  38. const reducer = (state, action) => {
  39. const act = Actions[action.type];
  40. const update = act(state, action.payload);
  41. return { ...state, ...update };
  42. };
  43.  
  44. export const StoreProvider = ({ children }) => {
  45. const [state, dispatch] = useReducer(reducer, initialState);
  46. return <StoreContext.Provider value={{ state, dispatch }}>{children}</StoreContext.Provider>;
  47. };
  48.  
  49. StoreProvider.propTypes = {
  50. children: PropTypes.node
  51. };
  52.  
  53. export const useStore = store => {
  54. const { state, dispatch } = useContext(StoreContext);
  55. return { state, dispatch };
  56. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement