gpt4 book ai didi

javascript - 可以用 `onEnter` 延迟组件渲染吗?

转载 作者:行者123 更新时间:2023-11-29 19:10:13 25 4
gpt4 key购买 nike

我正在使用 React Router onEnter 属性来处理身份验证,如下所示,也如 "auth-flow" example 中所示.

   function requireAuth(nextState, replace, next) {
Auth.validateToken()
.then(() => {
next();
})
.fail(() => {
replace('/login');
next();
});
}

<Router history={history}>
<Route path="/" component={App} >
<IndexRoute
component={Dashboard}
onEnter={requireAuth}
/>
<Route
path="login"
component={LogInForm}
/>
</Route>
</Router>

我正在使用 onEnter 的异步回调功能,因为我的 token 验证需要服务器调用。

我遇到的问题是,此示例中的 Dashboard 组件在调用 next() 之前呈现/安装。理想情况下,渲染会等到回调被触发。

我是否误解了它的工作原理?有没有办法延迟路由组件的渲染,直到某些条件为真?

最佳答案

永远不要延迟路线渲染,您的用户值得拥有更好的服务。

绝对有一种不同的方法可以做到这一点,那就是让你呈现的实际页面包含查看是否有人被授权查看它的逻辑,以及一个起始 state 类似 authorized: false,并且您的回调使用 this.setState({ authorized: resultFromCallback }) 切换。

该状态更改将导致 React 在您的页面上再次调用 render()如果值不同,然后在您页面的 render() 函数,您只需检查 this.state.authorized 以查看您是否应该向用户呈现一个 UI,其中包含他们应该作为匿名用户看到的所有位,或者他们应该看到的所有位作为授权用户。

...
componentDidount() {
whateverlib.checkForAuthorization(this.handleAuthorization);
},
handleAuthorization(authorized) {
this.setState({ authorized });
},
render() {
if(this.state.authorized) {
return this.renderAuthorizedUI();
}
return this.renderAnonymousUI();
},
...

还要记住,您的应用程序仍然只是在网页上运行的 JavaScript,那么您为什么还要检查您加载的每个页面?您需要做的就是检查任何页面,存储结果,然后完成。只要用户保持他们的选项卡打开,他们的授权状态就不会自发地从一个 react-router 应用程序管理的页面更改为下一个,因此您可以使用应用程序全局跟踪器。

var authorizer = require('./lib/whatever-thing-you-wrote-for-this');

var YourPage = React.createClass({
...
componentDidMount() {
if (!authorizer.isAuthorized()) {
authorizer.tryAuthorize(this.handleAuthorization);
}
},
handleAuthorization() {
this.forceUpdate();
},
render() {
if(authorizer.isAuthorized()) {
return this.renderAuthorizedUI();
}
return this.renderAnonymousUI();
},
...
});

关于javascript - 可以用 `onEnter` 延迟组件渲染吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39540921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com