我已经实现了标题。每当单击标题内的链接Portfolio
时,路由都会更改-我想另外触发其他组件的(CardHolder
)函数。我该怎么办?
组件尚未连接。
function App() {
return (
<BrowserRouter>
<div className="App">
<Header/>
...
<CartHolder />
</div>
</BrowserRouter>
);
}
const header = () => {
return (
<div className="Header container-fluid">
<div className="row">
<div className="col-6">
</div>
<div className="col-6">
<ul>
<li>
<Link to="/">Portfolio</Link>
</li>
<li className="ml-4">
About
</li>
</ul>
</div>
</div>
</div>
);
};
BTW CartHolder
是基于类的组件。
答案 0 :(得分:2)
您可以使用pathname
和CartHolder
来监听useEffect
内部useLocation
的变化,检查pathname
并调用函数(如果这是投资组合路线)>
import { useLocation } from 'react-router-dom'
const CartHolder = () => {
const { pathname } = useLocation()
const fn = () => {
console.log('portfolio')
}
useEffect(() => {
if (pathname === '/') {
fn()
}
}, [pathname])
return ...
}
对于基于类的组件,您将需要使用withRouter
HOC包装该组件,以便从react-router-dom
注入道具
然后在componentDidUpdate
中检查路线是否为投资组合路线,但还要检查先前的路线是否与投资组合不同,因为componentDidUpdate将在每次重新渲染时触发
import { withRouter } from 'react-router-dom'
class CartHolder extends Component {
fn = () => {
console.log('portfolio')
}
componentDidUpdate = prevProps => {
const prevPathname = prevProps.location.pathname;
const { pathname } = this.props.location;
if (pathname === "/" && pathname !== prevPathname) {
this.fn()
}
}
render() {
return...
}
}