[英]State is not gatting update when using setstate in react with hooks
我面临一个关于setstate的问题。 我想做以下步骤:
当我尝试将该特定博客添加到博客 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 正在更新。
提前致谢:)
getBlog()
在getBlogs()
的 fetch 完成之前运行,因此没有要过滤的blogs
。 getBlog()
的内容可以移动到 getBlogs( .then()
中的getBlogs()
,但这不是一个好主意:blog
不需要是 state ,因为它可以从blogs
和 params 派生; 那么你应该只使用useMemo
。FixURL
不需要是内部 function。 将其移到组件外部更清洁。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.