简体   繁体   English

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

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

in the return of my react function I want to do a response.data.map(...), but I can't, "response" is undefined because it's in my useEffect (scope problem).在我的反应函数的返回中,我想做一个 response.data.map(...),但我不能,“响应”是未定义的,因为它在我的 useEffect(范围问题)中。

So I try to create a state with useState which will contain response.data, but the problem is that my console.log always returns undefined, the default state of my state.所以我尝试使用 useState 创建一个包含 response.data 的状态,但问题是我的 console.log 总是返回 undefined,这是我状态的默认状态。

So I try to use prevstate because I believe the problem is that the previous state is taken into account, but apparently the syntax is not good.所以我尝试使用 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>
      
    
  );
};

I finally try to do like this:我终于尝试这样做:

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

This time the syntax is good, but my console.log from allComments is still undefined ...这次语法很好,但是我的来自 allComments 的 console.log 仍然未定义......

How do I access my response.data from my return?如何从我的退货中访问我的 response.data? Should we use useState, prevstate, other?我们应该使用useState、prevstate还是其他?

You can't .map() over an object ( {} ).您不能在对象 ( {} ) 上使用.map() )。

If your comments will be an array, you'll need to use the array spread operator ( [..., ...] ):如果您的注释是一个数组,则需要使用数组展开运算符 ( [..., ...] ):

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