[英]Nothing was returned from render; trying to redirect to homepage
I'm working on a school project with react, and I'm having difficulties redirecting to a page.我正在处理一个带有 React 的学校项目,但在重定向到页面时遇到了困难。 I'm using react-router-dom to navigate.我正在使用 react-router-dom 进行导航。 In my code, I try to redirect to the homepage by history.push("/")
if the test array doesn't contain anything.在我的代码中,如果测试数组不包含任何内容,我尝试通过history.push("/")
重定向到主页。 If I change the else rendering condition to a random p tag, it will render that text, but I just want it to redirect in the else statement.如果我将 else 呈现条件更改为随机 p 标记,它将呈现该文本,但我只是希望它在 else 语句中重定向。
edit: the error happens when refreshing the page, the url is being pushed.编辑:刷新页面时发生错误,正在推送 url。 So if i refresh again, I am at the homepage.所以如果我再次刷新,我在主页。
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('/')
);
}
};
When you want to change the url within a function , use history.push
.当您想更改函数内的 url 时,请使用history.push
。 When its based on something you render , you should use the Redirect
.当它基于你渲染的东西时,你应该使用Redirect
。
In this case, you should be using Redirect
like below:在这种情况下,您应该像下面这样使用Redirect
:
} else {
return(
<Redirect to="/" />
);
}
If you were changing the page based on say a button click, then history.push
would be appropriate.如果您根据按钮单击更改页面,则history.push
将是合适的。
<button onClick={() => history.push('/')}>Go to Home</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.