英文:
Why my state doesn't update after get value?
问题
我有一个状态应该填充API的响应。
这是我的代码
const [name, setName] = useState(null)
useEffect(() => {
decryption(Cookies.get("__n")).then(res => setName(utf8.decode(res)));
}, [])
但是我的代码在不刷新页面的情况下不会更新。为什么在useState中设置新值后不会重新渲染?
当我在没有useEffect
的情况下使用setName
时,没有发生重新渲染。
这是我的解密函数
export const decryption = async (value) => {
const response = await axios.post(
"https://00000",
JSON.stringify({
value: value,
}),
{
headers: {
// ....
},
}
);
if (response.data.status === "DONE") {
return response.data.result.value;
} else {
toast.error("An error occurred");
}
};
英文:
I have a state that should fill with a response of api.
this is my code
const [name,setName] = useState(null)
useEffect(()=>{
decryption(Cookies.get("__n")).then(res=>setName(utf8.decode(res)));
},[])
but my code doesn't update without refresh page. why this doesn't re-render after set new value in useState?
when i use setName without useEffect its no render happened
this is my decryption function
export const decryption = async (value) => {
const response = await axios.post(
"https://00000",
JSON.stringify({
value: value,
}),
{
headers: {
....
},
}
);
if(response.data.status==="DONE"){
return response.data.result.value;
}else{
toast.error("خطایی رخ داده است")
}
};
答案1
得分: 1
使用useEffect
,一个空的依赖数组意味着内部的函数仅在挂载时运行。
将name
添加到你的依赖数组中,以便它将会监视并在name
发生更改时重新运行。
const [name, setName] = useState(null);
useEffect(() => {
decryption(Cookies.get("__n")).then(res => setName(utf8.decode(res)));
}, [name]);
英文:
With useEffect, an empty dependency array means the function inside will only run on mount.
Adding name to your dependency array so that it will watch and rerun every time name is changed.
const [name,setName] = useState(null)
useEffect(()=>{
decryption(Cookies.get("__n")).then(res=>setName(utf8.decode(res)));
},[name])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论