同步渲染有问题

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 的用户的名字。


在这种情况下,我该怎么做才能让返回代码等到它获得用户的名字并只显示“嗨,我是约翰”,而不是在获得响应之前呈现“嗨,我没有改变”后台服务器和更改临时值?


蓝山帝景
浏览 62回答 1
1回答

慕侠2389804

一旦承诺履行,您可以使用标志通知您。如果不是,则向 DOM 返回一个空值。const Temp = () => {&nbsp; const [temp, setTemp] = useState("Not Changed");&nbsp; const [isLoaded, setIsLoaded] = useState(false);&nbsp; const SERVER_URL = "http://localhost:8000";&nbsp; const token = Cookies.get("token");&nbsp; const config = {&nbsp; &nbsp; headers: {&nbsp; &nbsp; &nbsp; Authorization: `Jwt ${token}`,&nbsp; &nbsp; },&nbsp; };&nbsp; Axios.get(`${SERVER_URL}/accounts/4`, config)&nbsp; &nbsp; .then((res) => {&nbsp; &nbsp; &nbsp; setTemp(res.data.data.first_name);&nbsp; &nbsp; &nbsp; // set flag to true once the val you want is received&nbsp; &nbsp; &nbsp; setIsLoaded(true);&nbsp; &nbsp; })&nbsp; &nbsp; .catch((err) => {&nbsp; &nbsp; &nbsp; console.log(err);&nbsp; &nbsp; });&nbsp; // display only once temp is set with val from server&nbsp; if (isLoaded) {&nbsp;&nbsp; &nbsp; return <h1>HI I'm {temp}!!</h1>;&nbsp; }&nbsp; // return null to display empty&nbsp;&nbsp; return null;};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript