如何使用React Hooks列出减速器?

时间:2019-05-06 23:47:56

标签: reactjs react-hooks

我正在使用React Hooks而不是Redux。我希望某些状态是全局的,可以通过任何组件访问。

现在我是这样的:

const App = () => {
  return (
    <Store>
      <Fragment>
        <GlobalStyle />
        <Routes />
      </Fragment>
    </Store>
  );
};
export default App;

在我的App.js文件中,导入商店组件,即:

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

export const StoreContext = createContext({});

const initialState = {
  rates: null,
  loading: true,
  error: false
};

function reducer(state, action) {
  switch (action.type) {
    case "UPDATE_RATE":
      return {
        ...state,
        rates: action.payload,
        loading: false
      };
    default:
      throw new Error("Action type must be defined");
  }
}

const Store = ({ children }) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <StoreContext.Provider value={[state, dispatch]}>
      {children}
    </StoreContext.Provider>
  );
};

export default Store;

这确实很好,但是,如果我需要创建更多的全局状态,我该如何做才能在更多文件中破坏代码(所需的全局状态数)并将它们全部传递给Store零件?我该如何在组件中称呼它们?

0 个答案:

没有答案