猿问

代码块在 api 调用获得响应之前运行

第二个 useEffect 块在第一个收到任何数据之前运行。这会导致第二个块返回一个错误和一个空数组。


我试过使用 async/await,因为这在过去为我解决了这样的问题。但是,它似乎在这里没有影响。


    const [session, setSession] = useState("");

    const [champions, setChampions] = useState([]);


    useEffect(() => {

        axios.get(`http://api.paladins.com/paladinsapi.svc/createsessionJson/${devId}/${generateSignature('createsession')}/${moment.utc().format('YYYYMMDDHHmmss')}`).then((response) => {

            setSession(response.data.session_id);

            console.log(session);

        }).catch((error) => {

            console.log(error);

        })

    }, [])


    useEffect(() => {

        axios.get(`http://api.paladins.com/paladinsapi.svc/getchampionsJson/${devId}/${generateSignature('getchampions')}/${session}/${moment.utc().format('YYYYMMDDHHmmss')}/1`).then((response) => {

            setChampions(response.data);

            console.log(champions);

        }).catch((error) => {

            console.log(error);

        })

    }, []);

它应该向冠军返回一个对象数组,但由于它没有收到会话 ID,因此 api 调用不是将冠军保持为空数组的正确地址。


繁星点点滴滴
浏览 113回答 2
2回答

holdtom

useEffect 是一个异步函数,因此您只需将调用移动到一个 useEffect 函数中,然后同步调用您的 api。我会将它移到一个单独的函数中,并使用 async/await 同步运行您的 api 调用。然后在 useEffect 函数中调用该函数,如下所示:useEffect(() => {  getData();},[]);const getData = async () => {  try{    const session = await axios.get(`your first call here`);    const champions = await axios.get(`your second call here`);    setSession(session.yourData);    setChampions(champions.yourData);  }catch(err){    console.log(err);  }} 如果您有第二个使用的第一个 api 调用的数据,那么您不需要将其设置为任何状态对象,您可以直接在第二个 api 调用中使用它。

翻阅古今

    const [session, setSession] = useState("");    const [champions, setChampions] = useState([]);    useEffect(() => {  try{    const session = await axios.get(`http://api.paladins.com/paladinsapi.svc/createsessionJson/${devId}/${generateSignature('createsession')}/${moment.utc().format('YYYYMMDDHHmmss')}`);    setSession(session.session_id);    const champions = await axios.get(`http://api.paladins.com/paladinsapi.svc/getchampionsJson/${devId}/${generateSignature('getchampions')}/${session.session_id}/${moment.utc().format('YYYYMMDDHHmmss')}/1`);    setChampions(champions );     }catch(err){    console.log(err);     }}, [])
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答