简体   繁体   English

State 在使用 setstate 与钩子反应时没有更新

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

I am facing an issue regarding the setstate .我面临一个关于setstate的问题。 I want to do the following steps:我想做以下步骤:

  1. I m fetching some blogs from the server.我正在从服务器获取一些博客。
  2. Adding blogs data to blogs state将博客数据添加到博客 state
  3. Filtering a blog that is the same as URL param过滤与URL param相同的博客
  4. Adding that blog to blog state将该博客添加到博客 state

problem is coming at stape 4 when I am trying to add that particular blog to the blog state.当我尝试将该特定博客添加到博客 state 时,问题出现在第 4 阶段。 When I am logging both states, the blog state is coming as empty array [].当我记录这两种状态时,博客 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 <>...</>;
}

I also tried to warp this setBlog into callback function but does work for me, not gatting why the blog state is gating updated.我还尝试将此 setBlog 扭曲为回调 function 但确实对我有用,不知道为什么博客 state 正在更新。

Thanks in Advance:)提前致谢:)

  1. getBlog() runs before getBlogs() 's fetch finishes, so there are no blogs to filter over. getBlog()getBlogs()的 fetch 完成之前运行,因此没有要过滤的blogs The contents of getBlog() could be moved to the .then() in getBlogs() , but that's not a good idea: getBlog()的内容可以移动到 getBlogs( .then()中的getBlogs() ,但这不是一个好主意:
  2. blog doesn't need to be state anyway, since it can be derived from blogs and params; blog不需要是 state ,因为它可以从blogs和 params 派生; you should just use useMemo then.那么你应该只使用useMemo
  3. There is no need for FixURL to be an inner function. FixURL不需要是内部 function。 It's cleaner to move it outside the component.将其移到组件外部更清洁。
  4. I assume you want a single blog (article) since the state atom is named blog , so I changed .filter to find .我假设您想要一个博客(文章),因为 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