显示信息React Native

6kkfgxo0  于 2022-11-25  发布在  React
关注(0)|答案(1)|浏览(126)

我试图在后端显示检索到的信息。恢复工作很顺利,但当我使用"array.push"将这些信息放入数组时,它不起作用。我还尝试使用useState,但由于某种原因,我的程序在无限循环中运行。

  1. import React, {useState} from "react";
  2. import {View, Text, Image} from "react-native";
  3. import AsyncStorage from "@react-native-async-storage/async-storage";
  4. const jwtDecode = require("jwt-decode");
  5. import {useDispatch} from "react-redux";
  6. import * as authAction from "../redux/actions/authAction";
  7. const FavoriteScreen = (props) => {
  8. const [id, setId] = useState("");
  9. const [informations, setInformations] = useState([]);
  10. const dispatch = useDispatch();
  11. let array = [];
  12. const checkToken = async () => {
  13. const token = await AsyncStorage.getItem("token");
  14. if (!token) {
  15. console.log("coucou le token n'existe pas");
  16. Alert.alert("Vous n'êtes pas connecté à un compte existant");
  17. return;
  18. }
  19. const decoded = jwtDecode(token);
  20. setId(decoded._id);
  21. };
  22. checkToken();
  23. dispatch(authAction.Favorite(id))
  24. .then((response) =>
  25. response.array.map((data) => {
  26. array.push(data);
  27. setInformations(array);
  28. })
  29. )
  30. .catch((error) => {
  31. console.error(error);
  32. });
  33. return (
  34. <View>
  35. {informations.map((data) => {
  36. <Text>{data["image_url"]}</Text>;
  37. })}
  38. </View>
  39. );
  40. };
  41. export default FavoriteScreen;
6ojccjat

6ojccjat1#

目前,您正在经历一个无限循环,因为您的API调用是在组件的“呈现端”被调用的。
另外一个问题是,API调用不会等待id被填充,因此我们需要在进行API调用之前等待令牌id
功能组件

  1. import React, { useState } from "react";
  2. import { View, Text, Image } from "react-native";
  3. import { useDispatch } from "react-redux";
  4. import AsyncStorage from "@react-native-async-storage/async-storage";
  5. const jwtDecode = require("jwt-decode");
  6. const FavoriteScreen = (props) => {
  7. const [informations, setInformations] = useState([]);
  8. const dispatch = useDispatch();
  9. const getToken = async () => {
  10. const token = await AsyncStorage.getItem("token");
  11. if (!token) {
  12. console.log("coucou le token n'existe pas");
  13. Alert.alert("Vous n'êtes pas connecté à un compte existant");
  14. return "";
  15. }
  16. const decoded = jwtDecode(token);
  17. return decoded._id;
  18. };
  19. useEffect(async () => {
  20. const id = await getToken();
  21. if (!id) return;
  22. dispatch(authAction.Favorite(id))
  23. .then((response) => {
  24. const newArray = response.array;
  25. setInformations(newArray);
  26. })
  27. .catch((error) => {
  28. console.error(error);
  29. });
  30. }, []);
  31. return (
  32. <View>
  33. {informations.map((data, index) => (
  34. <Text key={`information_${index}`}>{data["image_url"]}</Text>
  35. ))}
  36. </View>
  37. );
  38. }
  39. export default FavoriteScreen;

注意:这样,它就相当于组件生命周期中的componentDidMount

展开查看全部

相关问题