如何在useEffect中更新状态对象

时间:2020-07-16 16:46:19

标签: reactjs use-effect

如何在useEffect中更新状态对象

大家好,

在我的React应用程序中,我正在打电话给在线服务,以获取一些WIFI信息。最终,我想向用户显示\渲染wifiData的信息。

const [macAddress, setMacAddress] = useState('');
const [wifiData, setwifiData] = useState({});

const axios = require("axios");
const ClientOAuth2 = require('client-oauth2')
const clientAuth = new ClientOAuth2({
    accessTokenUri: 'https:....',
    clientId: '....',
    clientSecret: '....',
    scopes: ['....']
})

const wifiService = useCallback(() => {
    clientAuth.credentials.getToken().then(function (user) {
        if (user.accessToken) {
            axios({
                method: "post",
                url: "....access_token=" + user.accessToken,
                data: {
                   ....,
                },
            }).then(function (response) {
                // setwifiData ??
                console.log(response.data)
            }).catch(function (error) {
                console.log(error);
            });
        }
    })
}, [axios, clientAuth.credentials, macAddress])

useEffect(() => {
    if (!openDrawer && macAddress !== "") {
        wifiService();
       // setwifiData ??
    }
}, [wifiService, clientAuth.credentials, openDrawer, macAddress]);

return (
    <div style={{ padding: 20 }}>
     // render wifiData
)

如何将响应数据存储在wifiData中?

应对这种情况的正确方法是什么?我不知道。

感谢帮助

谢谢

1 个答案:

答案 0 :(得分:1)

设置wifiService()中的状态:

const wifiService = useCallback(() => {
    clientAuth.credentials.getToken().then(function (user) {
        if (user.accessToken) {
            axios({
                method: "post",
                url: "....access_token=" + user.accessToken,
                data: {
                   ....,
                },
            }).then(function (response) {
                // ** put response in correct format here if you need to
                setwifiData(response)
                console.log(response.data)
            }).catch(function (error) {
                console.log(error);
            });
        }
    })
}, [axios, clientAuth.credentials, macAddress])

从useEffect触发器中删除wifiService,以防止无限循环:

useEffect(() => {
    if (!openDrawer && macAddress !== "") {
        wifiService();
    }
}, [clientAuth.credentials, openDrawer, macAddress]);