简体   繁体   English

如何使用 React-Router 传递位置 state 和 URL 参数?

[英]How to pass location state and URL params using React-Router?

When I click on the link in the HoverBooks Component to get to a new page where I can render the book location state in Book component, but when I press on it nothing happens.当我单击HoverBooks组件中的链接进入一个新页面时,我可以在Book组件中呈现book位置 state,但是当我按下它时没有任何反应。 I think the error is in Route :我认为错误在于Route

function App() {
  return (
    <div className="App">
      <Router>
        <Switch>
          <Route path="/book:/book.Key">
            <Book />
          </Route>
          <Route path="/signin">
            <Signin />
          </Route>
          <Route path="/">
            <Header />
            <Home />
          </Route>
        </Switch>
      </Router>
    </div>
  )
}

export default App

import React from 'react'
import { useLocation } from 'react-router-dom'
const Book = () => {
  const {
    state: { book },
  } = useLocation()
  console.log({ book })
  return (
    <div key={book.key}>
      <h1>{book.bookName}</h1>
    </div>
  )
}

export default Book

const HoverBooks = ({ ...book }) => {
  const [inHoverBooks, setInHoverBooks] = React.useState(false)
  return (
    <>
      <Link
        to={{
          pathName: `/book/${book.key}`,
          state: {
            book,
          },
        }}
      >
        <img
          onMouseLeave={() => setInHoverBooks(false)}
          onMouseEnter={() => setInHoverBooks(true)}
          src={book.image}
          key={book.key}
        />
      </Link>
      {inHoverBooks && (
        <div className="hover__containter">
          <h3>{book.bookName}</h3>
          <h2>{book.by}</h2>
          <h2>{book.Narreted}</h2>
          <h2>{book.length}</h2>
          <h2>{book.rating}</h2>
        </div>
      )}
    </>
  )
}
export default HoverBooks

Below is the correct form, eg /:someName , to define a route with URL params :下面是使用URL 参数定义路由的正确形式,例如/:someName

<Route path="/book/:bookKey">
  <Book />
</Route>

And here is the right syntax to make a Link for the above route:这是为上述路线创建Link的正确语法:

<Link
  to={{
    pathname: `/book/SOME_BOOK_KEY`, // replace SOME_BOOK_KEY with some value
    state: {
      book,  // e.g. const book = { key: 'js', bookName: 'Learn JavaScript'}
    },
  }}
>
  <img src="some_src" alt="something" />
</Link>

And you useParams and useLocation react-hooks to access the "URL params" and "location state" in a component:并且您使用ParamsuseLocation react-hooks 来访问组件中的“URL 参数”和“位置状态”:

const Book = () => {
  const {
    state: { book },
  } = useLocation()
  const { bookKey } = useParams();

  console.log(book, bookKey) 
  // prints "book" object (from location state) and "bookKey" (from URL params)

  return (
    <div key={book.key}>
      <h1>{book.bookName}</h1>
    </div>
  )
}

I would suggest you to add typescript to your ReactJS app.我建议您将typescript添加到您的 ReactJS 应用程序中。 It helps you find errors early by doing "static Type-checking".它通过执行“静态类型检查”帮助您及早发现错误。

With react router you need to pass the component you want to render to the Route like this使用反应路由器,您需要像这样将要渲染的组件传递给Route

const ComponentA = (props) => {...}

<Route path="/component-a" component={ComponentA} />

And here is how to link to component a这里是如何链接到组件 a

<Link to="/component-a" >Go to component A</Link>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM