带路由的条件渲染

Conditional rendering with routing

我想使用路由进行条件渲染 - 当条件 true 替换为 SignUp 组件并为其提供 URL.

的路径名时

现在的方式将保留以前的组件路径名(例如可以是 /search
我该怎样做才对?

现在是这样 - 但注册页面在 url 中没有路径名。

 return (
    <div >
      {userAccount ? (
            <SignUp />    
      ) : (
        <>
          <Header
          />
          <div>
            <Switch>
              <Route exact path='/'>
                <Home />
              </Route>
              <Route exact path='/search'>
                <Search
                />
              </Route>
              </Switch>
               </div> 
                 </> )}
                  </div> );

不工作 -

这样它就不会显示 SignUp 页面组件,只有空白页面 前一个路径名

    {userAccount ? (
      <Switch>
      <Route exact path='/signup'>
        <SignUp />
      </Route>
    </Switch> ) :

这是解决方案 - 我在同一个 onClick 函数中按下了 history 并使用了 useState()。 从 return 回来,我只用 history.goBack()

做了同样的事情

App.js

const [userAccount, setUserAccount] = useState(false);  

return (
    <div >
      {userAccount ? (
      <Route exact path='/signup'>
        <SignUp />
      </Route>  :
        <>
          <Header/>
          <div>
            <Switch>
              <Route exact path='/'>
                <Home />
              </Route>
              <Route exact path='/search'>
                <Search
                />
              </Route>
              </Switch>
               </div> 
                 </> )}
                  </div> );

Header.jsx

      <button onClick={() {setUserAccount(true);
        history.push("/signup")}}>SIGN UP 
     </button>
       

SignUp.jsx

  <button
        onClick={() => {
          setUserAccount(false);
          history.goBack(); }} >
        SIGN OUT 
 </button>
           

感谢所有帮助过的人!