所以说我有这个全局JS函数文件,其他组件可以使用它来进行剩余调用,如果响应是未经授权的,我希望它将React组件的状态更改为LoggedIn:false。这可能吗?
答案 0 :(得分:0)
看起来像redux的用例。您将在商店中维护已登录,并将需要此信息的任何组件与商店连接。
否则,还有另外两种方法,我称其为hack。 1)在url查询参数中维护此参数,并在component中读取参数。 2)在sessionStorage或localStorage中维护它。 3)维护在window.isLoggedIn
但是由于这是与登录相关的信息,所以我将避免使用这些方式。对于其他一些全局变量,可以使用上述方法。
在这里看看redux https://redux.js.org/basics/usagewithreact
答案 1 :(得分:0)
class SomeComponent extends React.Component {
...
async getData() {
await response = fnToGetData();
if (response.unauthorized) {
this.props.setAuthorizationStatus(false);
// or if you want to set authorization only in this component
// this.setState(() => ({authorized: false}));
} else {
// do sth with the data
}
}
}
setAuthorizationStatus
位于应用程序顶部的某个位置,并通过props向下传递(您也可以使用上下文将其向下传递)。