我想使用meteor(v1.3)创建一个基于用户的应用程序。因此,身份验证和授权是应用程序的核心。 我遇到了 Flow Router 作者编写的这个优秀示例,它解释了如何使用 Flow Router 进行身份验证和授权。
https://github.com/alanning/meteor-roles/tree/master/examples/flow-router-advanced 然而,本示例使用 Blaze 进行演示。我想知道是否可以用 React 做同样的事情。
对我来说,将其转换为 React 最困难的部分是,它使用模板级别进行站点范围的身份验证。此时我不知道如何在react中完成它。
假设我有一个主要布局组件:
export const MainLayout = ({content}) => (
<div className="container">
{content}
</div>
);
如何在此布局中进行身份验证? 虽然,我知道我可以在路由器中做到这一点,但流路由器的全部要点是非 react 性和可预测的。 Flow router的作者也建议在模板层进行,就像他在上面的例子中所做的那样。
React 对我来说是个新事物,我可能误解了 React 的概念。因此,如果你们认为这不是理想的方法,请引导我走上正确的道路。
最佳答案
要将 Meteor 的响应式变量绑定(bind)到 Meteor 1.3+ 中的 React 组件,请使用 createContainer
函数:
export const MainLayout = createContainer(() => {
return {
isAdmin: Roles.userIsInRole(Meteor.userId(), ['admin']),
userName: Meteor.user() ? Meteor.user().username : null
}
}, (props) => {
if (!props.isAdmin) {
return <p>No cake for you.</p>
}
return <div className="container">
<p>Hello {props.userName}</p>
{props.content}
</div>;
});
createContainer
使用您提供的回调函数的返回值扩展 props
对象。如果您在该函数中访问 react 性值(如上面的 Meteor.user()
),则只要该值发生变化,就会重新计算该值。在浏览器控制台中输入 Meteor.logout()
,然后观察组件立即使用react。
有关完整的教程,请查看 https://www.meteor.com/tutorials/react/collections .
关于javascript - React js主组件中的身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36680003/