[英]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.