首页 > 解决方案 > 如果满足条件,则将路由器链接到新组件

问题描述

嗨,我在搞乱一些基本的用户身份验证。我有一个函数可以检查数据库中是否有匹配的用户名,如果找到它返回用户,如果不返回 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>

在此先感谢您的帮助:)

标签: reactjstypescriptreact-router

解决方案


如果您正在使用反应路由器,您可以使用推送功能,

检查这个答案使用反应路由器编程导航,也反应路由器历史对象


推荐阅读