当我点击HoverBooks
组件中的链接进入一个新页面时,我可以在Book
组件中呈现book
位置状态,但当我按下它时,什么都不会发生。我认为错误在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
以下是用URL参数定义路由的正确形式,例如/:someName
:
<Route path="/book/:bookKey">
<Book />
</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>
并且您使用Params和useLocation react钩子来访问";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>
)
}
我建议您在ReactJS应用程序中添加typescript。它可以帮助你尽早发现错误;静态类型检查";。
使用react路由器,您需要将要渲染的组件传递给Route
,如
const ComponentA = (props) => {...}
<Route path="/component-a" component={ComponentA} />
以下是如何链接到组件
<Link to="/component-a" >Go to component A</Link>