将嵌套对象从 Axios 响应复制到我的 React-native 挂钩?

Copy nested objects from Axios response to my React-native hook?

我只是想将从 axios GET 请求返回的嵌套对象复制到我的 react-native 挂钩。看起来并不简单。例如,数据看起来像这样:

[
  {
    _id: 61242b08013a5f26bd1b2d47,
    user: '6110675d65e1528d03a8bce6',
    totalCalories: 7,
    totalProtein: 7,
    createdAt: 2021-08-23T23:11:04.076Z,
    updatedAt: 2021-08-24T00:53:38.621Z,
    __v: 0
  },
  {
    _id: 6125990e9669cc6b466c37b5,
    user: '6110675d65e1528d03a8bce6',
    __v: 0,
    createdAt: 2021-08-25T01:12:44.343Z,
    totalCalories: 2,
    totalProtein: 2,
    updatedAt: 2021-08-25T01:14:01.439Z
  }
]

但是,当我尝试通过前端的 historyData 访问它时,出现 component exception: undefined is not an object 错误以及 404 错误。这是我的组件,它在我的 iOS 应用程序中呈现历史屏幕:

前端:

const History = () => {
    const [currentUsersID, setCurrentUsersID] = React.useState("");
    const [historyData, setHistoryData] = React.useState();

    // Gets the current user's ID from local storage
    const getData = async () => {
        try {
            const value = await AsyncStorage.getItem("@storage_Key");
            if (value !== null) {
                setCurrentUsersID(value);
            }
        } catch (error) {
            console.log("Error reading AsyncStorage value -> " + error);
        }
    };
    getData();

    async function getHistory() {
        try {
            const response = await axios.get("http://localhost:5000/daysLog/getLog/" + currentUsersID);
            setHistoryData(() => {
                return response.data;
            });
        } catch (error) {
            console.log("ERROR (getHistory) -> " + error);
        }
    }
    useFocusEffect(
        React.useCallback(() => {
            getHistory();
        })
    );
    return (
        <SafeAreaView style={styles.container}>
            <StatusBar barStyle="light-content" />
            <Text style={{ color: "white" }}>
                History: {historyData[0].totalCalories} // ERROR HERE
            </Text>
        </SafeAreaView>
    );
};

后端:

const router = require("express").Router();
let daysLog = require("../models/daysLog.model");

// getting the user's existing daysLogs
router.route("/getLog/:userID").get((req, res) => {
    daysLog
        .find({
            user: req.params.userID,
        })
        .then((logs) => res.json(logs))
        .catch((error) =>
            res.status(400).json("Error (dayLog/GET) -> " + error)
        );
});

historyData[0].totalCalories 正在抛出它,因为在您等待响应时获取它需要时间。在呈现结果之前,您应该有一个块来测试 historyData 是否不为空。

同时获得历史焦点效果依赖于 currentUser 有效,但没有表达式可以确保它按照您编写的方式使用。充其量它是一个竞争条件。考虑将焦点效果更改为调节效果,并使 currentUserId 成为依赖项。

然后在其中您可以检查 currentUserId 是否不为 null 并相应地开始获取获取历史记录。