复杂的业务逻辑应该用 React Context 去哪里?

时间:2021-02-22 17:41:13

标签: javascript reactjs

如果我想使用 Context 来存储从更复杂的 API 响应中解析出来的数据,我应该在哪里解析 API 响应?

React 文档中的 Theme example 相当简单:

export const themes = {
  light: {
    foreground: '#000000',
    background: '#eeeeee',
  },
  dark: {
    foreground: '#ffffff',
    background: '#222222',
  },
};

export const ThemeContext = React.createContext(
  themes.dark // default value
);

如果这个 themes 对象来自 API 并且我需要先对它进行一些额外的解析,那么最好的地方在哪里?

  • 在 api 调用之后,例如在反应钩子里面?那么传递给 Provider 的 value 已经被解析了吗?
<ThemeContext.Provider value={myParsedData}>
   <Toolbar changeTheme={this.toggleTheme} />
</ThemeContext.Provider>
  • 在提供者中?
  • 在 setTheme 函数中的提供程序中?
  • 其他地方?

答案是否会根据 theme 值是否改变而改变?

0 个答案:

没有答案