使用USENAVITAIGE的React通过无法读取NULL的属性
我正在使用USENAVITAITE将数据传递在组件之间。
import { useNavigate } from "react-router-dom";
function Categories() {
const navigate = useNavigate();
.
.
onClick={() => navigate("/books", {state:{ name: categorie.name }})}
然后,我从第二个组件中依靠其工作正常的数据
import {useLocation} from "react-router-dom";
function Books() {
const location = useLocation();
let currentcategory = location.state.name;
,但是如果我尝试使用URL https:// localhost/books直接访问
此错误,我会收到此错误
Uncaught TypeError: Cannot read properties of null (reading 'name')
I'm using useNavigate to pass data between components.
import { useNavigate } from "react-router-dom";
function Categories() {
const navigate = useNavigate();
.
.
onClick={() => navigate("/books", {state:{ name: categorie.name }})}
Then I resive the data from second component
import {useLocation} from "react-router-dom";
function Books() {
const location = useLocation();
let currentcategory = location.state.name;
Its works fine but If I try to access directly using URL https://localhost/books
I got this error
Uncaught TypeError: Cannot read properties of null (reading 'name')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题
问题是,如果您从提供状态的组件过渡,则仅存在路由/链接/导航状态 。如果您在地址栏中手动输入接收路由的URL路径,则该状态丢失或未定义/空。
换句话说,
location.state
是未定义的/null,并且在进一步访问它以获取location.state.state.name
时会抛出错误。解决方案
使用null-Check/Guard-Clause或可选的链式操作员来防御潜在的无效访问,或者为破坏性提供后备价值。
null-Check/guard-clause
可选的链接操作员
从
破坏的后备对象
Issue
The issue is that the route/link/navigate state only exists if you transition from the component providing the state. If you manually enter the receiving route's URL path in the address bar, this state is missing, or undefined/null.
In other words,
location.state
is undefined/null, and the error is thrown when accessing further into it to getlocation.state.name
.Solution
Use a null-check/guard-clause or the Optional Chaining operator to defend against the potentially null access, or provide a fallback value to destructure from.
Null-check/guard-clause
Optional Chaining operator
Fallback object to destructure from
你需要破坏它
you need to destructure it