繁体   English   中英

反应:我无法从我的 useEffect 访问我的状态

[英]React : i can't access to my state from my useEffect

在我的反应函数的返回中,我想做一个 response.data.map(...),但我不能,“响应”是未定义的,因为它在我的 useEffect(范围问题)中。

所以我尝试使用 useState 创建一个包含 response.data 的状态,但问题是我的 console.log 总是返回 undefined,这是我状态的默认状态。

所以我尝试使用 prevstate ,因为我认为问题是考虑了以前的状态,但显然语法不好。

const Comments = ({ postId }) => {

  // States 
  const [allComments, setAllComments] = useState()
  
  useEffect(() => {
    async function fetchData() {
      const data = {
        postId: postId,
      };
      const response = await POST(ENDPOINTS.GET_ALL_COMMENTS, data);
      if (response.data[0]) {
        setAllComments((prevState) => ({
          ...prevState,
          response.data
                    
        }))
      } else {
        
      }
    }
    fetchData();
    console.log(allComments)
  }, []);
  
  return (
           
      <div>
       {allComments.map(...)}
      </div>
      
    
  );
};

我终于尝试这样做:

setAllComments ((prevState) => ({
          ... prevState,
          response
          
        }))

这次语法很好,但是我的来自 allComments 的 console.log 仍然未定义......

如何从我的退货中访问我的 response.data? 我们应该使用useState、prevstate还是其他?

您不能在对象 ( {} ) 上使用.map() )。

如果您的注释是一个数组,则需要使用数组展开运算符 ( [..., ...] ):

const Comments = ({ postId }) => {
  const [allComments, setAllComments] = useState([]);

  useEffect(() => {
    async function fetchData() {
      const response = await POST(ENDPOINTS.GET_ALL_COMMENTS, {
        postId,
      });
      const data = response.data;
      if (Array.isArray(data)) {
        setAllComments((prevState) => [...prevState, ...data]);
      } else {
        throw new Error("Oops, didn't get an array.");
      }
    }
    fetchData();
  }, [postId]);

  return <div>{JSON.stringify(allComments)}</div>;
};

暂无
暂无

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

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