最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

TypeError:无法读取未定义的属性(读取“名字”)

网站源码admin27浏览0评论

TypeError:无法读取未定义的属性(读取“名字”)

TypeError:无法读取未定义的属性(读取“名字”)

我是新来的反应和节点(快递) 我正在尝试从数据库中获取一些日期(“firstName”和“lastName”),将它们连接起来并显示在一个选择标签中。

我做的是:

我在节点文件中发送到数据库的请求:

app.get("/employeesName", (req, res) => {
  db.query("SELECT firstname , lastname FROM employees", (err, result) => {
    if (err) {
      console.log(err);
    } else {
      res.send(result);
    }
  });
});

react中的get请求:

const [employeeList, setEmployeeList] = useState([]);
  useEffect(() => {
    const  getEmployeesNames = () => {
      Axios.get("http://localhost:3001/employeesName").then((response) => {
        setEmployeeList(response.data);
      });
      }; 
          getEmployeesNames();

  },[])

我尝试了类似的方法来在选择标签中复制我的数据:

 <select>
        <option value="">{employeeList[0].firstname+" "+employeeList[0].lastname}</option>
        <option value="">{employeeList[1].firstname+" "+employeeList[1].lastname}</option>         
 </select>

当我在 vs 代码中这样做时它有效,但就在我刷新页面时在浏览器中出现错误(无法读取未定义的属性),我认为 employeeList 在第一次渲染时为空。这是合理的,因为我的初始状态是一个空数组 (useState([]);),我尝试初始化 我的 useState 有类似的东西

useState([{firstname: 'test', lastname: 'test2'}]);
但仍然出现错误

应该怎么做才能避免这个错误?

回答如下:
useState([{firstname: 'test', lastname: 'test2'}])

这个数组只有一个元素所以

employeeList[1]
会是 falsy


您可以有条件地渲染选择:

{
    employeeList.length > 0 && (
        <select>
            {
                employeeList.map((emp, index) => <option key={index} value={index}>{emp.firstname + " " + emp.lastname}</option>)
            }
        </select>)
}
发布评论

评论列表(0)

  1. 暂无评论