javascript - 重定向延迟导致临时显示不正确的组件

标签 javascript reactjs

遇到问题时我想根据逻辑重定向页面。

因此,如果我重定向,应该只转到我正在重定向的页面,而不显示 MyComponent 中的组件。

确实发生了重定向,但有 1 - 2 秒的延迟。
在此期间,出现了不该显示的组件。
有没有办法阻止这种情况并只是重定向?

注意:此组件已最小化以专注于此问题。实际组件还有更多内容。

可以在这个最小项目中观察到该问题。 https://github.com/kvaithin/react-routing-issue

const MyComponent = () => {
  const [data, setData] = useState();

  // just a temp call to emulate getting data
  useEffect(() => {
    fetch("https://api.npms.io/v2/search?q=react")
      .then((response) => response.json())
      .then((d) => setData(d));
  }, []);

  // i want this redirect to happen without seeing the text below.
  useEffect(() => {
    const redirect = true;
    if (redirect) {
      // some other logic that will determine if redirect = true
      window.location.replace("https://hn.algolia.com/api/v1/search?query=redux");
    }
  }, []);

  return (
    <div>
      I should never reach here cos of the redirect But I still see this text briefly for a second
      or 2 before redirecting.
      {/* other components inside here  */}
    </div>
  );
};

export default MyComponent;

最佳答案

"The function passed to useEffect will run after the render is committed to the screen" .如果您想在执行逻辑之前阻止显示内容,您可以使用 checking 状态,如下所示:

const MyComponent = () => {
  const [data, setData] = useState();
  const [checking, setChecking] = useState(true);

  useEffect(() => {
    fetch("https://api.npms.io/v2/search?q=react")
      .then((response) => response.json())
      .then((d) => setData(d));
  }, []);

  useEffect(() => {
    const redirect = true;
    if (redirect) {
      setChecking(false);
      window.location.replace("https://hn.algolia.com/api/v1/search?query=redux");
    }
  }, []);

  if (checking) return null; // or a loading message or component

  return (
    <div>
      I should never reach here cos of the redirect But I still see this text briefly for a second
      or 2 before redirecting.
    </div>
  );
};

export default MyComponent;

关于javascript - 重定向延迟导致临时显示不正确的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73838484/

相关文章:

javascript regexp 不只计算一个字符

javascript - 为什么我的图片不会出现在 ReactJS 中?

javascript - 是的,使用正则表达式进行验证并且不区分大小写

javascript - x 秒后淡出模态框

javascript - React 中 onChange 或 onSubmit 中是否将表单输入保存到状态

reactjs - 单击时更改按钮的样式

javascript - 解释如何在 REACT 中删除引导卡

javascript - 是否有不同类型的转义序列?

javascript - Chrome 调试器显示未定义但确实有一个值

javascript - 如何使用 jQuery 平滑地隐藏和显示按钮?