簡體   English   中英

如何添加將使用 react-router-dom 渲染組件的路由?

[英]How to add a route that will render a component using react-router-dom?

目前,以下代碼位於組件SinglePostPage中:

        <section>
            <article className="post">
                <h2>{post.title}</h2>
                <p className="post-content">{post.content}</p>
                <Link to={`editPost/${post.id}`} className="button">
                    Edit Post
                </Link>
            </article>
        </section>

EditPostForm組件包含用於編輯帖子的表單。 當有人單擊Link時,如何添加路由以呈現EditPostForm組件?

我的App.js如下:

function App() {
  return (
    <Router>
      <Navbar />
      <div className="App">
        <Switch>
          <Route
            exact
            path="/"
            render={() => (
              <React.Fragment>
                <AddPostForm/>
                <PostsList/>
              </React.Fragment>
            )}
          />
          <Route exact path="/posts/:postId" component={SinglePostPage} />
          <Redirect to="/" />
        </Switch>
      </div>
    </Router>
  )
}

export default App

我相信您可以向 App.js 添加一條新路由。 例如:

function App() {
  return (
    <Router>
      <Navbar />
      <div className="App">
        <Switch>
          <Route
            exact
            path="/"
            render={() => (
              <React.Fragment>
                <AddPostForm/>
                <PostsList/>
              </React.Fragment>
            )}
          />
          <Route exact path="/posts/:postId" component={SinglePostPage} />
          <Route exact path="/editPost/:id" component={EditPostForm} />
          <Redirect to="/" />
        </Switch>
      </div>
    </Router>
  )
}

export default App;

然后在 SinglePostPage 中,您的鏈接路徑略有錯誤,應該是:

<Link to={`/editPost/${post.id}`}>...</Link>

你錯過了第一個'/'

暫無
暫無

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

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