最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass location state and URL params using React-Router? - Stack Overflow

programmeradmin4浏览0评论

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 ponent, but when I press on it nothing happens. I think the error is in 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

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 ponent, but when I press on it nothing happens. I think the error is in 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
Share Improve this question edited Mar 19, 2021 at 17:59 Ajeet Shah 19.9k9 gold badges64 silver badges104 bronze badges asked Mar 19, 2021 at 15:21 mura1mura1 4821 gold badge6 silver badges22 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Below is the correct form, e.g. /:someName, to define a route with URL params:

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

And here is the right syntax to make a Link for the above route:

<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 ponent:

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. It helps you find errors early by doing "static Type-checking".

With react router you need to pass the ponent you want to render to the Route like this

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

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

And here is how to link to ponent a

<Link to="/ponent-a" >Go to ponent A</Link>
发布评论

评论列表(0)

  1. 暂无评论