同步渲染遇到麻烦

时间:2020-08-05 06:55:02

标签: javascript reactjs asynchronous

const Temp = () => {
  const [temp, setTemp] = useState("Not Changed");
  const SERVER_URL = "http://localhost:8000";
  const token = Cookies.get("token");
  const config = {
    headers: {
      Authorization: `Jwt ${token}`,
    },
  };
  Axios.get(`${SERVER_URL}/accounts/4`, config)
    .then((res) => {
      setTemp(res.data.data.first_name);
    })
    .catch((err) => {
      console.log(err);
    });
  return <h1>HI I'm {temp}!!</h1>;
};

export default Temp;

当我执行代码时,屏幕最初显示“嗨,我没有改变”,不久之后更改为“嗨,我是约翰”,其中约翰是用户的名字,ID号为4。< / p>

在这种情况下,我该怎么做才能使返回码一直等到它获得用户的名字并只显示“ Hi I'm John”,而不是先显示“ Hi I'm Not Changed”,然后再显示后台服务器的响应并更改temp的值?

1 个答案:

答案 0 :(得分:1)

您可以使用标志在诺言履行后通知您。

如果没有,请向DOM返回一个空值。

const Temp = () => {
  const [temp, setTemp] = useState("Not Changed");
  const [isLoaded, setIsLoaded] = useState(false);
  const SERVER_URL = "http://localhost:8000";
  const token = Cookies.get("token");
  const config = {
    headers: {
      Authorization: `Jwt ${token}`,
    },
  };
  Axios.get(`${SERVER_URL}/accounts/4`, config)
    .then((res) => {
      setTemp(res.data.data.first_name);
      // set flag to true once the val you want is received
      setIsLoaded(true);
    })
    .catch((err) => {
      console.log(err);
    });
  // display only once temp is set with val from server
  if (isLoaded) { 
    return <h1>HI I'm {temp}!!</h1>;
  }
  // return null to display empty 
  return null;
};