簡體   English   中英

如何在我的 ReactJS 應用程序中使用 React Router 設置路由?

[英]How to setup Routes using React Router in my ReactJS app?

我對 react-router 有一些問題。 當我點擊id時,它不會 go Edit頁面。 id在 URL 中,但它什么也沒做。

const Main = (props) => {
    const { pathname } = props.location;
    
    return (
        <Fragment>
            <div>
                <div className="container">
                    <Header />
                    {pathname === "/create" ? <Create /> : null}
                    {pathname === '/edit/:id' ? <Edit /> : null}
                    {pathname === "/" ? <Home /> : null}

                </div>
            </div>
        </Fragment>
    );
};

export default withRouter(Main);

應用程序.js:

require('./components/Index');

import React from 'react'
import ReactDOM from "react-dom"

import Index from "./components/Index";
import { BrowserRouter as Router} from "react-router-dom";
import { ToastContainer } from 'react-toastify';
const App =() =>{

}

if (document.getElementById('app')) {
    ReactDOM.render(<Router> <Index />  <ToastContainer /></Router>, document.getElementById('app'));
}

index.js:

import React from "react";
import { Route, Switch } from "react-router-dom";
import Main from "./CRUD/Main";
import Create from "./CRUD/Create";
import Edit from "./CRUD/Edit";
import Home from "./CRUD/Home";

const Index = (props) => {
    return (
        <Main>
                <Switch>
                    <Route path="/Create" component={Create} />
                    <Route path='/edit/:id' component={Edit} />
                    <Route exact path="/" component={Home} />
                </Switch>
        </Main>
    );
};

export default Index;

我認為main.jspathname有一些問題。

使用react-router時,您不需要像在Main中那樣進行條件渲染 Switch將自動渲染與該位置匹配的第一個子<Route><Redirect>

因此,您需要從路由器組件(即Index )中刪除Main ,使其如下所示:

const Index = (props) => {
  return (
    <>
      <NavBar /> {/* NavBar is optional, I just added for example */}
      <Switch>
        <Route path="/create" component={Create} />
        <Route path="/edit/:id" component={Edit} />
        <Route exact path="/" component={Home} />
      </Switch>
    </>
  );
}

NavBar: ( Link s; 僅用於示例)

function NavBar() {
  return (
    <ul>
      <li>
        <Link to="/create">Go to create</Link>
      </li>
      <li>
        <Link to="/edit/123">Go to edit with id = 123</Link>
      </li>
      <li>
        <Link to="/">Go to home</Link>
      </li>
    </ul>
  );
}

現在,當您單擊上述鏈接時,它會自動將您帶到相關組件(如路由中聲明的那樣,即Index )。 無需手動條件檢查

例如,要使用useParams鈎子在Edit組件中檢索URL 參數,即id

function Edit() {
  const { id } = useParams<{ id: string }>(); // Remove <{ id: string }> if not using TypeScript
  return <h2>Edit, {id}</h2>;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM