在React中重新渲染组件时变量未定义

时间:2020-10-09 15:09:28

标签: reactjs

在我的应用中,我有大学系的列表。单击特定部门后,您将进入部门登录页面(/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>
  );
};

1 个答案:

答案 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