【问题标题】:How to run a code only when user changes page in React js?仅当用户在 React js 中更改页面时如何运行代码?
【发布时间】:2021-12-23 15:45:50
【问题描述】:

让 React 应用有 4 个页面(page1, page2, page3, page4)。

我只想在用户从 page3 移动到任何其他页面时运行代码,即在更改页面之前。

【问题讨论】:

标签: reactjs react-hooks react-router react-router-dom


【解决方案1】:

我建议创建一个包装器组件,在组件卸载时在回调中调用所需的代码。

示例包装器组件:

const UnmountCallback = ({ children, onUnmount }) => {
  useEffect(() => onUnmount, []);
  return children;
};

react-router-dom v6

使用UnmountCallback 包装器组件为您想要调用的组件渲染路由和组件。

const unMountCallback = () => console.log("Left page 3!!");

...

<Routes>
  <Route path="/page1" element={<Component1 />} />
  <Route path="/page2" element={<Component2 />} />
  <Route
    path="/page3"
    element={
      <UnmountCallback onUnmount={unMountCallback}>
        <Component3 />
      </UnmountCallback>
    }
  />
  <Route path="/page4" element={<Component4 />} />
</Routes> 

react-router-dom v4/5

如果您仍在使用 react-router-dom 的 v5,则过程类似,您切换到 render 属性并渲染一个匿名组件。

<Switch>
  <Route path="/page1" component={Component1} />
  <Route path="/page2" component={Component2} />
  <Route
    path="/page3"
    render={(props) => (
      <UnmountCallback onUnmount={unMountCallback}>
        <Component3 {...props} />
      </UnmountCallback>
    )}
  />
  <Route path="/page4" component={Component3} />
</Switch>

【讨论】:

    【解决方案2】:

    您可以做的是将state 从第 3 页传递到第 4 页,并将其作为依赖项添加到第 4 页组件的挂载中,然后使用观察者(如useEffect)只运行一个块第 4 页组件收到此 state 时的代码。

    伪代码:

    路由定义的父组件

    const Parent = () => {
      return (
        <BrowserRouter>
          <Switch>
            <Route path={'/page1'} component = {Page1}/>
            <Route path={'/page2'} component = {Page2}/>
            <Route path={'/page3'} component = {Page3}/>
            <Route path={'/page4'} component = {Page4}/>
          </Switch>
        </BrowserRouter>
      )
    }
    
    

    Page3 组件,链接到第 4 页并将其自己的路径名(即路由名)作为道具传递

    const Page3 = () => {
      const location = useLocation()
      return (
        <div>
          <Link to={{pathname: '/page4', state: { prevPath: location.pathname }}}>Example Link</Link>
        </div>
      )
    }
    
    

    Page4 组件接收我们刚刚来自的页面的位置。

    如果接收到的位置是 Page3 的位置,我们运行一些代码

    
    const Page4 = ({location}) => {
      const path = location.state.prevPath
      const isComingFromPageThree = path === "/page3"
    
      if (isComingFromPageThree) {
        console.log('run this code')
      }
    
      return (
        <div>
          page 4
        </div>
      )
    }
    
    

    这是基于组件接收到的一些 props 呈现组件的另一种方法,组件可以使用这些 props 有条件地运行一些代码。 Reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 2015-03-01
      • 2020-12-13
      • 1970-01-01
      相关资源
      最近更新 更多