简体   繁体   English

如何将全局变量传递给所有组件-React JS

[英]how to pass global variables to all components - react js

I have a shopping cart website and I should pass some value to all components. 我有一个购物车网站,应该为所有组件传递一些价值。 for example when the user logged in the website I stored some value of user to localStorage . 例如,当用户登录网站时,我将用户的一些值存储到localStorage now, most components need to know about these values. 现在,大多数组件都需要了解这些值。

my question is I should retrieve these values inside each component (inside componentDidMount function)? 我的问题是我应该在每个组件(在componentDidMount函数内部)内检索这些值吗?

of course I know about redux . 我当然知道redux but I have a problem with redux when the user refresh page I lose data. 但是当用户刷新页面我丢失数据时, redux出现了问题。

If you use redux. 如果您使用redux。 You can persist and rehydrate the store to the local storage or IndexedDB using a store enhancer, such as redux-persist . 您可以使用商店增强程序(例如redux-persist)将商店持久化并重新补充到本地存储或IndexedDB中。

Another option is to use Use React's context . 另一个选择是使用Use React的context You can inject the data to the component's tree via the context provider, and all components would have access to it. 您可以通过上下文提供程序将数据注入到组件的树中,所有组件都可以访问它。

The context is described as: 上下文描述为:

Context provides a way to pass data through the component tree without having to pass props down manually at every level. 上下文提供了一种通过组件树传递数据的方法,而不必在每个级别手动传递道具。

Example of use (from React 16.3 documentation): 使用示例(来自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>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM