首页 > 解决方案 > 反应路线不导航

问题描述

我在 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 已被渲染。

我是否需要在当前代码中添加任何其他内容?

标签: javascriptreactjsreact-router

解决方案


您可以使用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

推荐阅读