Ionic 如果URL哈希值发生变化,如何激活效果?

j0pj023g  于 12个月前  发布在  Ionic
关注(0)|答案(1)|浏览(156)

我正在使用Ionic 7和React 18。如果URL的哈希部分发生变化,我想在容器中激活不同的组件。我已经尝试过这样做:

const MyContainer: React.FC<ContainerProps> = () => {
    ...

  useEffect(() => {
    // Set step based on the hash in the URL
    const hash = window.location.hash.substring(1); // Remove the '#' from the hash
    switch (hash) {
        ...
      case 'message':
        dispatch(setStep(StepsEnum.Message));
        break;
    }
  }, []);

    ...
        {step === StepsEnum.Name && <MyFirstComponent />}
        {step === StepsEnum.Address && <MySecondComponent  />}
        {step === StepsEnum.Message && <MyThirdComponent />}
      </IonContent>
    </IonPage>
  )
}

export default MyContainer

字符串
不幸的是,当我在浏览器中输入不同的哈希值时,什么都没有发生(至少,我没有看到useEffect被调用)。是否可以根据URL的哈希值激活不同的组件?

pkln4tw6

pkln4tw61#

除非你使用路由器,比如React Router,它提供了跟踪URL变化的钩子,否则你需要显式地监听hashchange事件。

示例(点击链接)

const { useState, useEffect } = React;

const MyContainer = () => {
  const [hash, setHash] = useState();

  useEffect(() => {
    const handleUrlChange = () => {
      setHash(window.location.hash.substring(1));
    };
    
    window.addEventListener('hashchange', handleUrlChange);
    
    return () => {
      window.removeEventListener('hashchange', handleUrlChange);
    };
  }, []);
  
  return (
    <div>
      <a href="#1">1</a>
      <a href="#2">2</a>
      <a href="#3">3</a>
      <a href="#4">4</a>
      {hash}
    </div>
  );
};

ReactDOM
  .createRoot(root)
  .render(<MyContainer />);
a {
  margin: 0.5em;
}
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

<div id="root"></div>

您可以将散列跟踪代码提取到useHash钩子(预期):

const { useState, useEffect } = React;

const useHash = () => {
  const [hash, setHash] = useState();

  useEffect(() => {
    const handleUrlChange = () => {
      setHash(window.location.hash.substring(1));
    };
    
    window.addEventListener('hashchange', handleUrlChange);
    
    return () => {
      window.removeEventListener('hashchange', handleUrlChange);
    };
  }, []);

  return hash;
};

const MyContainer = () => {
  const hash = useHash();
  
  return (
    <div>
      <a href="#1">1</a>
      <a href="#2">2</a>
      <a href="#3">3</a>
      <a href="#4">4</a>
      {hash}
    </div>
  );
};

ReactDOM
  .createRoot(root)
  .render(<MyContainer />);
a {
  margin: 0.5em;
}
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

<div id="root"></div>

现在,您可以使用useHash生成的hash触发useEffect

const MyContainer = () => {
  const hash = useHash();
  
  useEffect(() => {
    switch (hash) {
        ...
      case 'message':
        dispatch(setStep(StepsEnum.Message));
        break;
    }
  }, [hash]);

相关问题