执行不同组件的功能

时间:2019-12-21 19:15:58

标签: javascript reactjs

我已经实现了标题。每当单击标题内的链接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是基于类的组件。

1 个答案:

答案 0 :(得分:2)

您可以使用pathnameCartHolder来监听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...
  }
}