繁体   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