如何将全局变量传递给所有组件 - 反应js

时间:2018-04-05 19:43:52

标签: javascript reactjs

我有一个购物车网站,我应该将一些价值传递给所有组件。例如,当用户登录网站时,我将一些用户值存储到localStorage。现在,大多数组件需要了解这些值。

我的问题是我应该在每个组件内部检索这些值(在componentDidMount函数内部?)

当然我知道redux。但是当用户刷新页面丢失数据时,redux出现问题。

1 个答案:

答案 0 :(得分:2)

如果你使用redux。您可以使用商店增强程序(例如redux-persist)将商店持久化并重新水化到本地存储或IndexedDB。

另一种选择是使用Use React的context。您可以通过上下文提供程序将数据注入组件的树,并且所有组件都可以访问它。

上下文描述为:

  

Context提供了一种在没有组件树的情况下传递数据的方法   必须在每个级别手动传递道具。

使用示例(来自React 16.3文档):

// Create a context for the current theme (with "light" as the default).
const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    // Use a Provider to pass the current theme to the tree below.
    // Any component can read it, no matter how deep it is.
    // In this example, we're passing "dark" as the current value.
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

function ThemedButton(props) {
  // Use a Consumer to read the current theme context.
  // React will find the closest theme Provider above and use its value.
  // In this example, the current theme is "dark".
  return (
    <ThemeContext.Consumer>
      {theme => <Button {...props} theme={theme} />}
    </ThemeContext.Consumer>
  );
}