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

标签 javascript reactjs

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

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

我当然知道redux。但是当用户刷新页面时,我遇到了 redux 的问题,我丢失了数据。

最佳答案

如果你使用redux。您可以使用存储增强器将存储持久保存到本地存储或 IndexedDB,例如 redux-persist .

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

上下文描述为:

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

使用示例(来自 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>
  );
}

关于javascript - 如何将全局变量传递给所有组件 - React js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49680325/

相关文章:

javascript - 如何使用 style.left 从右向左移动图像?

javascript - 将模块暴露给外部删除别名

javascript - 面试编码时如何在短时间内用javascript实现一个队列?

javascript - 排序方法为何返回差异

javascript - 如何从包含大量数组的大 JSON 文件中发布必要的信息

javascript - 使用 jquery 检查 html 属性是否存在并且具有正确的值

javascript - React 多重动态路由

reactjs - 使用 react-pdf/render 库在 pdf 文档中渲染自定义 HTML 标记

javascript - React.js : disable DateTime when changed to the past

javascript - 从 Reactjs 中的 onClick 事件渲染组件内的组件