javascript - 反应路线不导航
问题描述
我在 App.js 中写了以下路线 -
function App() {
return (
<>
<BrowserRouter>
<Switch>
<Route path="/" exact component={Dashboard} ></Route>
<Route path="/details/:index" exact component={ItemDetails} ></Route>
<Dashboard></Dashboard>
</Switch>
</BrowserRouter>
</>
);
}
export default App;
我有另一个组件 - 有卡片(Reactstrap)的项目。每张卡都有一个链接 -
function Items(props) {
console.log(props.index.index)
return (
<Link to={{pathname:"/details",param1:props.index.index}}>
<Card tag="a" key={props.index.index} style={{display:'flex',width:'25%',flexWrap:'nowrap',float:'left',cursor: "pointer"}}
>
<CardBody>
<CardTitle> {props.card.card.value} </CardTitle>
</CardBody>
</Card>
</Link>
)
}
export default Items
在 Link 标记中,对于属性,我已经提到 -
to={{pathname:"/details",param1:props.index.index}}
通过这个我期待,点击卡片,组件 -ItemDetails
应该被渲染。但我看不到,ItemDetails 已被渲染。
我是否需要在当前代码中添加任何其他内容?
解决方案
您可以使用useHistory
轻松解决此问题的钩子
import React from 'react'
import {useHistory} from 'react-router-dom'
function Items({index, card}) {
const history = useHistory()
function navigateTo(){
history.push(`/details/${index.index}`)
}
return (
<Card onClick={navigateTo} tag="a" key={props.index.index} style={{display:'flex',width:'25%',flexWrap:'nowrap',float:'left',cursor: "pointer"}}
>
<CardBody>
<CardTitle> {card.card.value} </CardTitle>
</CardBody>
</Card>
)
}
export default Items
推荐阅读
- c++ - 为什么 std::istream_iterator 构造函数返回指针
- c# - 设备未订阅 oOneSignal 引发无推送令牌错误
- java - 为什么促销引擎在 Hybris 中不能正常工作?
- python - 使用 .loc 和日期检索值
- python - 无法打开数据库文件 - Mayan EDMS
- c# - 安装程序项目自定义操作 - 指定工作目录
- maven - Gradle 发布到私有存储库:无法获取资源 maven-metadata.xml
- python - 如何在 python 中使用 MySQL 的 NULL 和 DEFAULT 关键字进行 INSERT 查询?
- google-cloud-platform - 在 google composer 中安装 hadoopy
- c# - IEnumerator 或 IEnumerable 中的“产量”?