axios 我正在从后端获取对象数组,但无法将它们设置为React状态

hts6caw3  于 2023-05-12  发布在  iOS
关注(0)|答案(2)|浏览(83)

先谢了。我使用axios.get()获取后端数据,但是对象数组没有填充状态
它在控制台中给我以下。
Outside Effect {success: true, message: 'All Categories List', category: Array(2)} [] Outside Effect[object Object],[object Object]
后端代码也给出了。

const [categories,setCategories] =useState([])

const getAllCategory = async () => {
    try {
      const  {data}  = await axios.get("/api/v1/category/get-category");
      if (data.success) {
        console.log(data)
        setCategories(data.category);
        console.log(categories)
      }
    } catch (error) {
      console.log(error);
      toast.error("Something `enter code here`went wrong in getting category");
    }
  };

useEffect(() => {
    getAllCategory();
  }, []);
console.log("Outside Effect"+categories)

//后端代码

export const categoryController = async (req, res) => {
  try {
    const category = await categoryModel.find({});

    res.status(200).send({
      success: true,
      message: "All Categories List",
      category,
    });
  } catch (error) {
    console.log(error);
    res.status(500).send({
      success: false,
      message: "Error While Getting All Categories",
      error,
    });
  }
};
yyhrrdl8

yyhrrdl81#

其他的输入错误,setState下面的console.log(categories)将不会显示更新的类别,因为setState是异步进程。你可以为那个添加一个使用效果->

useEffect(() => {
    console.log(categories)
  }, [categories]);
qncylg1j

qncylg1j2#

给予这个:

const [categories, setCategories] = useState([]);

useEffect(() => {
  const loadData = async () => {
    try {
      const { data } = await axios.get("/api/v1/category/get-category");
      if (data.success) {
        setCategories(data.category);
      }
    } catch (error) {
      console.log(error);
      toast.error("Something `enter code here` went wrong in getting category");
    }
  };

  loadData();
}, []);

相关问题