javascript - 渲染没有返回任何内容;试图重定向到主页
问题描述
我正在做一个有反应的学校项目,我在重定向到一个页面时遇到了困难。我正在使用 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('/')
);
}
};
解决方案
当您想更改函数中的 url 时,请使用history.push
. 当它基于你渲染的东西时,你应该使用Redirect
.
在这种情况下,您应该使用Redirect
如下:
} else {
return(
<Redirect to="/" />
);
}
如果您基于说按钮单击来更改页面,那么history.push
将是合适的。
<button onClick={() => history.push('/')}>Go to Home</button>
推荐阅读
- google-cloud-platform - 如何在签名 URL 中加密/隐藏谷歌云存储桶名称
- javascript - 如何在Javascript中制作精确的睡眠功能,可能使用承诺?
- django - Django Custom 中间件不在每个页面中显示消息
- svelte - 无法使用 wavesurfer 读取 null 的属性“持续时间”
- android - 如何在类控制器之间同步包含 AsyncTask 和片段
- r - 无法将 x 比例从日期更改为数字
- mysql - 使用 Mysql DENSE_RANK() 函数从一些详细信息(id、主题、点)更改表以添加额外的列(排名)
- java - java.lang.string 类型的连接值无法转换为 jsonobject [Android Volley 库]
- odoo - 如何在odoo中添加自定义选择字段颜色
- c - 数组类型究竟是如何存储在 C 中的?