首页 > 解决方案 > 渲染没有返回任何内容;试图重定向到主页

问题描述

我正在做一个有反应的学校项目,我在重定向到一个页面时遇到了困难。我正在使用 react-router-dom 进行导航。history.push("/")在我的代码中,如果测试数组不包含任何内容,我会尝试重定向到主页。如果我将 else 渲染条件更改为随机 p 标签,它将渲染该文本,但我只想让它在 else 语句中重定向。

编辑:刷新页面时发生错误,正在推送网址。所以如果我再次刷新,我在主页上。

import React from "react";
import styles from "./Profile.module.css";
import { useParams } from "react-router-dom";
import { useStores } from "../../hooks/useStores";
import Trade from "../Trade/Trade";
import { useHistory } from "react-router-dom";

const Profile = () => {
  const history = useHistory();
  const stores = useStores();

  let { id } = useParams();
  const test = stores.dataStore.openTrades.filter(
    trade => trade.user.id.toString() === id
  );

  if (test.length > 0) {
    return (
      <>
        <div className={styles.profileHead}>
          <img
            src={process.env.PUBLIC_URL + "/assets/img/poke-logo.svg"}
            alt="profile icon"
            width="120"
            height="120"
          />
          <p
            className={styles.profileName}
          >{`Profile of ${test[0].user.name}`}</p>
        </div>
        <div className={styles.trades}>
          <h2 className={styles.profileTrades}>
            {`${test[0].user.name}'s trades`}{" "}
            <span className={styles.tradesLength}>({test.length})</span>
          </h2>
          <div className={styles.tradesColumn}>
            {test.map((trade, index) => (
              <Trade key={index} trade={trade} index={index}></Trade>
            ))}
          </div>
        </div>
      </>
    );
  } else {
    return(
    history.push('/')
    );
  }
};

标签: javascriptreactjsreact-routerjsx

解决方案


当您想更改函数中的 url 时,请使用history.push. 当它基于你渲染的东西时,你应该使用Redirect.

在这种情况下,您应该使用Redirect如下:

} else {
  return(
    <Redirect to="/" />
  );
}

如果您基于说按钮单击来更改页面,那么history.push将是合适的。

<button onClick={() => history.push('/')}>Go to Home</button>

推荐阅读