简体   繁体   English

为什么 useState() 没有设置默认值?

[英]Why is useState() not setting the default value?

I have created following reactComponent.我创建了以下 reactComponent。 From what I understand useState([]);据我了解 useState([]); should set the comments variable to an array.应该将 comments 变量设置为数组。 But it does not.但事实并非如此。 I get an exeption that I Try to run.map() on an object.我得到一个例外,我尝试在 object 上运行.map()。 What I have to do is Object.values(comments) to make it work but I don't understand why.我要做的是 Object.values(comments) 让它工作,但我不明白为什么。 My api definetly returns an array of comment objects.我的 api 明确地返回一个评论对象数组。

import React, { useState, useEffect } from 'react';
import axios from 'axios';

export default ({ postId }) => {
  const [comments, setComments] = useState([]);

  const fetchData = async () => {
    const res = await axios.get(
      `http://localhost:4001/posts/${postId}/comments`
    );

    setComments(res.data);
  };

  useEffect(() => {
    fetchData();
  }, []);

  const renderedComments = comments.map(comment => {
    return <li key={comment.id}>{comment.content}</li>;
  });

  return <ul>{renderedComments}</ul>;
};

Your use of state is correct as far as I can tell, the fact that Object.values works on the data handed back to you implies it is definitely either an object or an array, have you run Array.isArray(res.data) as part of your troubleshooting process?据我所知,您对 state 的使用是正确的,事实上Object.values对返回给您的数据有效,这意味着它绝对是一个Array.isArray(res.data)您的故障排除过程的一部分?

As stated by a commenter above, the most likely scenario is that you are getting an object back from your back end.正如上面评论者所说,最有可能的情况是您从后端获得了 object。 Other things you can do to confirm its the data handed back to you at fault would be to simply comment out your useEffect and see if it still throws the same exception.您可以做的其他事情来确认它是否有错误地返回给您的数据是简单地注释掉您的useEffect并查看它是否仍然抛出相同的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM