javascript - 如何在与 redux 的反应中实现从根 (index.js) 到根 (index.js) 的路由
问题描述
我正在编写一个反应服务器网页,试图从 index.js(即:localhost:3000)重定向到登录页面:(localhost:3000/login),并从登录到索引(以防登录失败)。我需要在 index.js 和 login.js 中写什么?
这适用于基于反应的应用程序,也使用 redux 框架。我尝试了几种方法,包括设置 BrowserRouter 等。所有这些都不会真正进行重定向。
我目前的代码是这样的:
在 index.js 中:
class Index extends Component {
static getInitialProps({store, isServer, pathname, query}) {
}
render() {
console.log(this.props);
//const hist = createMemoryHistory();
if (!this.props.isLoggedIn){
return(<Switch><Route exact path = "/login"/></Switch>)
}
else{...}
在 login.js 中:
render() {
console.log(this.props);
if (fire.auth().currentUser != null) {
var db = fire.firestore();
db.collection("users").doc(fire.auth().currentUser.uid).get().then((doc) => {
this.props.dispatch({ type: 'LOGIN', user: doc.data() });
})
}
const { isLoggedIn } = this.props
console.log(isLoggedIn)
if (isLoggedIn) return <Redirect to='/' />
如果没有会话打开,我除了 root 重定向到登录,一旦成功登录,登录重定向到 root。我目前在索引处收到“您不应该在 <Router> 之外使用 <Switch>”(我尝试使用 BrowserRouter、ServerRouter、Router 进行包装。第一个说它需要 DOM 历史记录。添加历史记录不会改变错误。另外两个不要出错,但在浏览器上显示为空白。)和登录时“ReferenceError:未定义重定向”。
任何帮助将不胜感激。
解决方案
您可以使用类似这样的 HOC(高阶组件)
export default ChildComponent => {
class ComposedComponent extends Component {
componentWillMount() {
this.shouldNavigateAway();
}
componentWillUpdate() {
this.shouldNavigateAway();
}
shouldNavigateAway() {
if (!this.props.authenticated) {
this.props.history.push('/')
}
}
render() {
return <ChildComponent {...this.props} />
}
}
}
推荐阅读
- angular - 从角度的url中检索查询参数
- python - setup.py 目标安装路径
- angular - 如何在不嵌套代码的情况下订阅另一个服务
- reactjs - 在 G 变换旋转中传递组件时出现错误
- javascript - React 最佳实践:如果我们不能在 JSX onChange() 中使用箭头函数,我们如何传入自定义参数?
- arcgis - Failure in creation of feature class: Unable to create object class extension COM component
- c# - C# - write to multiple files
- r - duplicates in agrep function
- node.js - 从Node JS检索图像获取服务器响应
- c# - 在 ListView 中跨越多列的列标题