首页 > 解决方案 > 在功能组件的返回中使用异步

问题描述

我有以下组件,但异步函数在功能组件的返回中不起作用。我基本上是在列表中进行交互以向 API 请求一些信息,但返回不起作用。获取了信息,但是当我构建测试返回 jsx 元素时它不起作用。

我不允许这样做吗?任何其他方式。请参阅下面的组件:

import React, { useEffect } from "react";
import "./usersWishlist.css";

import MainNavigation from "../mainNavigation/mainNavigation";
import Footer from "../footer/footer";

import { useDispatch, useSelector } from "react-redux";

import { storesUserSearchValueHandler } from "../../store/actions/searchValueFromNavbarHandler";
import { getItemsForUserWishlist } from "../../store/actions/actionsWishlist/requestItemsForUsersWishlist";
import { RootStore } from "../../store/store";
import axios from "axios";

// Types for the responses:

type movieResponse = {
  id: number;
  poster_path: string | null;
  backdrop_path: string | null;
  title: string;
  overview: string | null;
  vote_average: number;
  genres: { id: number; name: string }[];
  original_language: string;
  status: string;
};

type tvShowsResponse = {
  id: number;
  poster_path: string | null;
  backdrop_path: string | null;
  title?: string;
  name?: string;
  overview: string | null;
  vote_average: number;
  genres: { id: number; name: string }[];
  original_language: string;
  status: string;
};

const AddToWishlist: React.FC = () => {
  const dispatch = useDispatch();

  //  StoreSearchValue
  const configMDBState = useSelector(
    (state: RootStore) => state.postApiConfigurationReducer
  );

  //  StoreSearchValue
  const storeSearchValueHandlerState = useSelector(
    (state: RootStore) => state.searchValueFromInputHandlerR
  );

  // authetication logic
  const authenticationState = useSelector(
    (state: RootStore) => state.authenticationLogicR
  );

  //   wishlist state
  const wishlistItemsState = useSelector(
    (state: RootStore) => state.getItemsWishListR
  );

  useEffect(() => {
    dispatch(
      getItemsForUserWishlist(
        `https://living-room-3a1ec-default-rtdb.europe-west1.firebasedatabase.app/items.json?orderBy="itemOwnerId"&equalTo="${authenticationState.userId}"`
      )
    );
  }, [authenticationState.userId]);

  // closes the instant results div if user clicks outside the div. This is done in all the components
  const resetsUserSearchHandler = () => {
    if (storeSearchValueHandlerState.userSearchValue.length > 0) {
      dispatch(storesUserSearchValueHandler(""));
    }
  };

  return (
    <div className="wishlist-section" onClick={resetsUserSearchHandler}>
      <MainNavigation />
      <main className="wishlist">
        <div className="wishlist-title">
          <h2>Your living room list</h2>
        </div>
        <div className="list">
          {wishlistItemsState.payload &&
          wishlistItemsState.payload.length > 0 ? (
            wishlistItemsState.payload.map((item) => {
              if (item.type === "movie") {
                axios
                  .get(
                    `https://api.themoviedb.org/3/movie/${item.id}?api_key=${configMDBState.apiKey}&language=en-US`
                  )
                  .then((res) => {
                    const { id, poster_path, title, genres }: movieResponse =
                      res.data;
                    return (
                      <div>{`${id}, ${poster_path}, ${title}, ${genres}`}</div>
                    );
                  })
                  .catch((e) => {});
                return;
              }
              axios
                .get(
                  `https://api.themoviedb.org/3/tv/${item.id}?api_key=${configMDBState.apiKey}&language=en-US`
                )
                .then((res) => {
                  const { id, poster_path, title, genres }: tvShowsResponse =
                    res.data;
                  return (
                    <div>{`${id}, ${poster_path}, ${title}, ${genres}`}</div>
                  );
                })
                .catch((e) => {});
            })
          ) : (
            <div className="list-empty">
              <h2>Wishlist is empty</h2>
            </div>
          )}
        </div>
      </main>
      <Footer />
    </div>
  );
};

export default AddToWishlist;

我想要做的是迭代初始响应并请求我需要呈现 jsx 元素的信息。我是否必须将其移至 useEffect 并将此处的信息分配给新状态?我真的以为这是可能的...

标签: reactjsreact-hooksreact-functional-component

解决方案


推荐阅读