在我的应用中,我有大学系的列表。单击特定部门后,您将进入部门登录页面(/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
数组是作为道具从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>
);
};
答案 0 :(得分:0)
问题很可能与此有关,
useEffect(() => {
const unit = props.depts.find(item => item.Id === Number(id));
setDept(unit); // <<
}, [id]);
除setDept(unit);
外,您的代码集中没有其他状态
因此,我最好的猜测是props.depth
查找没有匹配项并返回null
。这就是为什么dept.Name
产生错误
从MDN,
满足提供的测试功能的数组中第一个元素的 value 。否则,将返回
undefined