使用 useEffect 钩子时状态值不会改变
state value does not change when using useEffect hook
我有:
const [bgColor, setBgcolor] = useState(false);
和:
useEffect(() => {
if (window.location.pathname === '/SignUp') {
setBgcolor(true);
} else {
setBgcolor(false);
}
console.log(bgColor)
return () => {
setBgcolor(false);
}
}, [])
我想做的是:当我重新加载页面或重新呈现页面时,我检查当前路径名是否等于 /Signup 我将 bgColor 设置为 true 但每次我重新加载时都给我 false!
试试这个:
const [bgColor, setBgcolor] = useState(false);
const { pathname } = window.location;
useEffect(() => {
if (pathname === '/SignUp') {
setBgcolor(true);
} else {
setBgcolor(false);
}
console.log(bgColor)
return () => {
setBgcolor(false);
}
}, [pathname]);
我有:
const [bgColor, setBgcolor] = useState(false);
和:
useEffect(() => {
if (window.location.pathname === '/SignUp') {
setBgcolor(true);
} else {
setBgcolor(false);
}
console.log(bgColor)
return () => {
setBgcolor(false);
}
}, [])
我想做的是:当我重新加载页面或重新呈现页面时,我检查当前路径名是否等于 /Signup 我将 bgColor 设置为 true 但每次我重新加载时都给我 false!
试试这个:
const [bgColor, setBgcolor] = useState(false);
const { pathname } = window.location;
useEffect(() => {
if (pathname === '/SignUp') {
setBgcolor(true);
} else {
setBgcolor(false);
}
console.log(bgColor)
return () => {
setBgcolor(false);
}
}, [pathname]);