[英]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:
我想做以下步骤:
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:)提前致谢:)
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()
,但这不是一个好主意: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
。FixURL
to be an inner function. FixURL
不需要是内部 function。 It's cleaner to move it outside the component.blog
, so I changed .filter
to find
.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.