为什么我的状态在获取值后不更新?

huangapple go评论98阅读模式
英文:

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]);

这里有关于useEffect中依赖数组的一些信息

英文:

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])

Here is some info on the dependency array in useEffect

huangapple
  • 本文由 发表于 2023年3月7日 19:24:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75661364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定