【问题标题】:Redirecting a user to a different path in React在 React 中将用户重定向到不同的路径
【发布时间】:2018-07-04 09:12:35
【问题描述】:

我正在构建一个网络应用程序。用户可以从 Firebase 中阅读有关对象的一些信息。问题是用户也可以使用 Android 应用程序登录,如果 Firebase 上的属性发生更改,他需要被踢出他在网络应用程序上的当前视图。我知道如何完成这个。这是代码:

var AssignedWordRef = firebase.database().ref('Users').child(currentUser.uid).child('assignedWork');
AssignedWordRef.on('value', snapshot => {
    var assignmentId = snapshot.val();
    if (assignmentId === null) {
        console.log('Redirect right here mate');
    }
});

这很有效。这是控制台日志记录,一切都很棒。但问题是我需要将用户重定向到不同的路径。到目前为止,我使用了window.location,但这是个坏主意。这是我的Routes

<Switch>
    <Route exact path="/assignments" render={
        () => (firebase.auth().currentUser === null ?
            <Redirect to='/'/> : this.state.assignedWord === undefined ?
                <AssignmentsComponent/> :
                <Redirect to={'/assignment/' + this.state.assignedWord}/>)
    }/>

    <Route exact path='/assignment/:id' render={
        props => (
            firebase.auth().currentUser === null ?
                <Redirect to='/'/> : <CheckIfHasCurrentTasksComponent {...props}/>)
    }/>

    <Route exact path='/userPanel' render={
        () => (firebase.auth().currentUser === null ?
            <Redirect to='/'/> : <UserPannelComponent/>)
    }/>

    <Route exact path="/" component={HomeComponent}/>
</Switch>

我尝试返回console.log 所在的&lt;ComponentToRedirectTo/&gt;,但没有成功。

返回 &lt;Redirect to='/assignments'/&gt; 也没有帮助。我的猜测是我必须把它放在Route,但我不知道怎么做。

【问题讨论】:

标签: javascript reactjs firebase firebase-realtime-database


【解决方案1】:

将 push 与 this.props.history 一起使用,或者仅使用重定向。这是来自another answer 的示例代码(记得使用this.setState)来执行新的渲染:

class MyComponent extends React.Component {
  state = {
    redirect: false
  }

  handleSubmit () {
    axios.post(/**/)
      .then(() => this.setState({ redirect: true }));
  }

  render () {
    const { redirect } = this.state;

     if (redirect) {
       return <Redirect to='/somewhere'/>;
     }

     return <RenderYourForm/>;
}

【讨论】:

    【解决方案2】:

    您可以尝试this.props.history.push('/');,而不是使用&lt;Redirect to='/' /&gt;

    希望这会奏效!

    【讨论】:

      猜你喜欢
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多