如何将react组件的一些值存储在broswer作用域中



我不知道我是否使用了正确的术语,但这正是我试图做的。我正在从我的一个API中获取一些头部详细信息,其中包括承载令牌和其他详细信息。这些值将被大多数其他反应组分使用。有没有一种方法可以在不使用Redux或将数据传递给所有单个组件的情况下全局存储数据?

下面是一个代码片段,它从React组件的位置状态中获取值。我需要在不使用redux的情况下全局存储这些值。

if (response.httpStatus === 200) {
setIsLoggedIn(true);
//setIsAdmin(response.user.isAdmin!);
setEmailAddress(inputEmailAddress);
history.push('/console',{
token:response.token,
companyID: response.user.companyID, 
firstName: response.user.firstName, 
lastName: response.user.lastName,
emailAddress: response.user.emailAddress 
} //<--- I also need to store this object globally in the browsers scope so that they can be used by all other react components. 
);
}

我的问题听起来可能很傻,而且可能缺乏正确的术语。我的工作主要是在API和数据库中。我没有太多使用react的专业知识或知识。

您可以使用这样的模式:

将数据存储到某个父状态并使用React.createContextReact.useContext

对于除少数组件之外的更复杂的应用程序,强烈建议您改用Redux。使用@reduxjs/toolkit是因为它使Redux代码不那么冗长,而且官方建议为大多数应用程序编写Redux代码。

function mockApi() {
return new Promise((resolve,reject) => {
setTimeout(() => resolve("API DATA"), 1000);
});
}
const GlobalContext = React.createContext(null);
function App() {
console.log("Rendering App...");
const [apiData,setApiData] = React.useState(null);

React.useEffect(() => {
mockApi().then((data) => {
setApiData(data);
});
},[]);
return(
<GlobalContext.Provider value={apiData}>
<SomeComponent/>
</GlobalContext.Provider>
);
}
function SomeComponent() {
const apiData = React.useContext(GlobalContext);
return(
apiData? 
<div>SomeComponent: {apiData}</div>
: <div>SomeComponent: Loading data...</div>
);
}
ReactDOM.render(<App/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>

使用上下文API,将帮助您学习和理解状态管理

示例:https://ibaslogic.com/react-context-api/

上下文对小项目来说很好,但Redux的表现更好。

很抱歉没有提到我在使用Ionic框架。我使用存储电容器来全局存储这些值。

最新更新