首页 > 解决方案 > 在 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>
  );
};

标签: reactjs

解决方案


问题很可能是这个,

  useEffect(() => {
    const unit = props.depts.find(item => item.Id === Number(id));
    setDept(unit); // <<
  }, [id]);

除了所以,你的代码中没有其他设置状态setDept(unit); ,我最好的猜测是props.depthfind 不匹配并返回null。这就是为什么dept.Name结果错误

来自MDN

数组中满足提供的测试函数的第一个元素值。否则,返回undefined


推荐阅读