我有一个购物车网站,我应该将一些值传递给所有组件。例如,当用户登录网站时,我将用户的一些值存储到 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/