我有the following code that redirects automatically to the About component when you load the FAQ component。这是通过使用自定义钩子完成的,该钩子使用useHistory()
向其推送新路由。自定义钩子还返回一个空对象。当您不尝试使用此对象中的任何内容时,代码可以正常工作,并且应用程序重定向到About组件。
但是,当我尝试从对象访问一个(不存在的)值时,出现value is null
错误。我不明白为什么代码甚至达到了这个目的。重定向是否应该在其余组件呈现之前进行?
import React from "react";
import "./styles.css";
import { Link, BrowserRouter, Route, useHistory } from "react-router-dom";
export default function App() {
return (
<div className="App">
<BrowserRouter>
<Link to="/about">About</Link>
<Link to="/faq">FAQ</Link>
<Route path="/about" component={About} />
<Route path="/faq" component={FAQ} />
</BrowserRouter>
</div>
);
}
function useRedirect() {
const history = useHistory();
history.push("/about");
return {};
}
function FAQ() {
const { value } = useRedirect();
return <h1>FAQ {value.name}</h1>;
}
function About() {
return <h1>About</h1>;
}
为什么在访问value
之前 不会发生重定向?以及如何在访问value
之前确保我的应用重定向?
答案 0 :(得分:1)
为什么在访问值之前重定向不会发生?如何 我可以确保我的应用在访问该值之前会重定向吗?
重定向确实在访问该值之前发生,但这并不意味着重定向代码下的其他源代码将不会执行。这就是客户端路由中的方式。
function TestComponent() {
const history = useHistory();
history.push("/about");
setTimeout(()=>{
console.log("foo"); // <-- will get executed regardless
}, 3000)
return "";
}
例如,如果要执行window.location.href
服务器端http请求重定向,则执行将取决于您的互联网速度
function TestComponent() {
window.location.href = "https://example.com";
setTimeout(()=>{
console.log("bar"); // <-- will probably not get executed - will depend on your internet speed
}, 3000)
return "";
}
我希望这可以消除对SPA重定向的一些潜在误解