簡體   English   中英

State 在使用 setstate 與鈎子反應時沒有更新

[英]State is not gatting update when using setstate in react with hooks

我面臨一個關於setstate的問題。 我想做以下步驟:

  1. 我正在從服務器獲取一些博客。
  2. 將博客數據添加到博客 state
  3. 過濾與URL param相同的博客
  4. 將該博客添加到博客 state

當我嘗試將該特定博客添加到博客 state 時,問題出現在第 4 階段。 當我記錄這兩種狀態時,博客 state 以空數組 [] 的形式出現。

function BlogDetail(props) {
  const [blog, setBlog] = useState([]);
  const [blogs, setBlogs] = useState([]);

  let param = useParams();

  // Fetch blogs from server
  const getBlogs = () => {
    axios
      .get("/blog/all_blog/")
      .then((res) => {
        setBlogs(res.data);
        console.log(res.data);
      })
      .catch((err) => console.log(err));
  };

  const getBlog = () => {
    const FixURL = (url) =>
      url
        .replace(/[^a-zA-Z ]/g, "")
        .replace(/\s+/g, "-")
        .toLowerCase();
    setBlog(blogs.filter((artical) => FixURL(artical.title) === param.id));
  };

  useEffect(() => {
    getBlogs();
    getBlog();
  }, []);

  console.log(blog);
  console.log(blogs);

  return <>...</>;
}

我還嘗試將此 setBlog 扭曲為回調 function 但確實對我有用,不知道為什么博客 state 正在更新。

提前致謝:)

  1. getBlog()getBlogs()的 fetch 完成之前運行,因此沒有要過濾的blogs getBlog()的內容可以移動到 getBlogs( .then()中的getBlogs() ,但這不是一個好主意:
  2. blog不需要是 state ,因為它可以從blogs和 params 派生; 那么你應該只使用useMemo
  3. FixURL不需要是內部 function。 將其移到組件外部更清潔。
  4. 我假設您想要一個博客(文章),因為 state 原子被命名為blog ,所以我將.filter更改為find
const FixURL = (url) =>
  url
    .replace(/[^a-zA-Z ]/g, "")
    .replace(/\s+/g, "-")
    .toLowerCase();

function BlogDetail(props) {
  const [blogs, setBlogs] = useState();
  const { id } = useParams();

  useEffect(() => {
    axios.get("/blog/all_blog/").then(({ data }) => setBlogs(data));
  }, []);

  const blog = React.useMemo(() => (blogs || []).find((article) => FixURL(article.title) === id));

  console.log(blog);
  console.log(blogs);

  return <>...</>;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM