我正在处理这个页面,我需要根据 type
过滤一些帖子。出于某种原因, useState 钩子没有更新数据。代码注释更好地描述了出错的地方。如何修复 useState 钩子?
澄清一下,filteredPosts
应该从 newFilteredPosts
获取一个新值。
页面.tsx
import React, { useEffect, useState } from "react";
import { PostType } from "types";
import { useStyles } from "styles";
import { useAppState, useAppDispatch } from "context/store";
import { getAllPosts, setActivePost } from "context/posts/postOperations";
import { selectBoard, getAllBoards } from "context/boards/boardOperations";
const Page = () => {
const dispatch = useAppDispatch();
const classes = useStyles();
const { posts, activePost, selectedBoardId, boards } = useAppState();
const [filteredPosts, setFilteredPosts] = useState(Array<PostType>());
useEffect(() => {
getAllBoards(dispatch);
}, [dispatch]);
const updateposts = () => {
getAllPosts(dispatch, selectedBoardId);
var newFilteredPosts = Array<PostType>();
posts.forEach((p) => p.type === "mobile" && newFilteredPosts.push(p));
setFilteredPosts(newFilteredPosts); // this doesn't seem to work
console.log(newFilteredPosts); // this prints data
console.log(filteredPosts); // this shows an empty array
}
...