【问题标题】:React Router link to new component if condition is met如果满足条件,则将路由器链接到新组件
【发布时间】:2020-09-08 14:31:11
【问题描述】:

您好,我在搞乱一些基本的用户身份验证。我有一个函数可以检查数据库中是否有匹配的用户名,如果找到它返回用户,如果没有返回 null。我的问题是,当返回用户时,我希望我的应用程序自动呈现我的仪表板页面,如果为 null 则留在同一个 userSelect 页面上。

  const [enteredUserName, setenteredUserName] = useState<string>("")  

  const login = async () => {
    const response = await fetch(`http://localhost:5000/login?name=${enterUserName}`, {
      method: "GET",
    })
    const data = await response.json();
    console.log(data)
    if (data !== null) {
      console.log("user Found")
       setLoggedInUserSettings(data)
      return(
        <Link to="/dashboard"/>
      )
    } 
  };
 return (
    <>
      <div>
          <input type="text" onChange={enteredUserName} />
          <button onClick={login}>Log In</button>
      </div>

这些是我在 App.tsx 中的路由,因此默认情况下,该应用会呈现 userSelect 屏幕。如果登录功能的结果是找到用户,我需要我的应用程序将我带到仪表板。

     <Route exact path='/' component={UserSelect} />
     <Route path='/setup' component={UserSetUp} />
     <Route path='/tracker' component={Tracker} />
     <Route path='/history' component={History} />
     <Route path='/settings'  component={SettingsForm} />
     <Route path="/dashboard" component={Dashboard} />
   </Switch>

提前感谢您的帮助:)

【问题讨论】:

    标签: reactjs typescript react-router


    【解决方案1】:

    如果你正在使用 react 路由器,你可以使用推送功能,

    检查这个答案Programmatically navigate using react routerreact router history object

    【讨论】:

      【解决方案2】:

      不要使用&lt;Link /&gt;,而是使用&lt;Redirect to="/dashboard"/&gt;(一定要从react-router导入)

      或者,如果您有可用的路由历史记录道具,请按以下方式使用:this.props.history.push('/dashboard'),为了访问历史记录,您可以使用名为 withRouter (withRouter docs) 的 HOC 包装您的组件

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-19
        • 2020-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多