reactjs - 在 React 中重新渲染组件时变量未定义
问题描述
在我的应用程序中,我有一个大学部门列表。当您单击特定部门时,您将被带到部门登录页面 ( /department/:deptId
)。我正在使用 React Router 的useParams
钩子从 URL 中获取部门 ID,然后从我的部门数组中找到作为道具传递的特定部门对象。
从部门列表导航到单个部门页面时,这工作正常,但如果我刷新页面,我会收到以下错误:Uncaught TypeError: can't access property "Name", dept is undefined
我的代码如下:
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
const Department = props => {
const { id } = useParams();
const [dept, setDept] = useState({});
useEffect(() => {
const unit = props.depts.find(item => item.Id === Number(id));
setDept(unit);
}, [id]);
return (
<div>
<h1>{dept.Name}</h1>
</div>
);
};
export default Department;
我不确定为什么会这样。我的理解是道具应该保持不变,并且useEffect
应该在页面刷新时运行。知道我错过了什么吗?
更多代码如下:
该depts
数组作为来自组件的 props 传递,该App
组件是从 Context API 组件中的 axios 调用中获取的。
import { UnitsContext } from './contexts/UnitsContext';
function App() {
const { units } = useContext(UnitsContext);
return (
<>
<Navigation />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/people" component={Persons} />
<Route exact path="/department/:id">
<Department depts={units} />
</Route>
</Switch>
</>
);
}
// Context Component. Provider wraps `index.js`
export const UnitsContext = createContext();
export const UnitsContextProvider = props => {
const url = 'http://localhost:5000';
const [units, setUnits] = useState([]);
useEffect(() => {
axios
.get(`${url}/api/units`)
.then(res => {
setUnits(res.data);
})
.catch(err => {
console.log(err);
});
}, []);
return (
<UnitsContext.Provider value={{ units }}>
{props.children}
</UnitsContext.Provider>
);
};
解决方案
问题很可能是这个,
useEffect(() => {
const unit = props.depts.find(item => item.Id === Number(id));
setDept(unit); // <<
}, [id]);
除了所以,你的代码中没有其他设置状态setDept(unit);
,我最好的猜测是props.depth
find 不匹配并返回null
。这就是为什么dept.Name
结果错误
来自MDN,
数组中满足提供的测试函数的第一个元素的值。否则,返回
undefined
推荐阅读
- vb.net - 如何减少 Binance API /api/v3/order 调用的延迟?
- node.js - Account disabled by Server Administrator - Firebase
- java - Changing Fragment From within another Fragment Android Java
- linux - How to ask a user for "sudo" permission in runtime in Go
- python - 如何在python中生成一个小于或等于另一个矩阵的随机矩阵
- python - How to bind or use radiobutton to make a selection use?
- python - Match pattern, then replace single character in it
- typescript - TSeD Mixed type Enum and Collection
- c# - Deserialize JSON into C#?
- javascript - 如何仅调整一个子元素的祖父样式,然后重置为正常?