访问钩子的数据-React

时间:2019-11-14 04:10:36

标签: json reactjs react-hooks

我正在请求此API,然后将结果保存在“数据”挂钩中。当我想打印“ data.total_results”时一切正常,但是当我要打印内部包含更多数据的键时,则不会留下“ Data.results [0] .title”

import React, { useState, useEffect } from 'react';

const Movie = () => {
  // Declara una nueva variable de estado, que llamaremos "count".
  const [Data, setData] = useState("");

  useEffect(() => {
    const Cargar = async () => {
      let respuesta = await fetch("https://api.themoviedb.org/3/discover/movie?api_key=ce322f54257cc9286282b320c5e9b2a0&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1");
      let respuestaJSON = await respuesta.json();
      setData(respuestaJSON);
    };
    Cargar();
  }, [Data]);
  return (
    <div>
      {Data.total_results}
      {/* {Data.results[0].title} */}
    </div>
  );
}

export default Movie;

4 个答案:

答案 0 :(得分:1)

您需要检查是否定义了results属性。

<div className="App">
  <h1>Total {Data.total_results}</h1>
  {typeof Data.results !== "undefined" &&
    Data.results.map((movie, index) => {
      return <h3>{movie.title}</h3>;
    })}
</div>

工作演示https://codesandbox.io/s/distracted-feather-4l55r

几天前,我创建了一个存储库并使用React实现了OMDB API。这可能对您有帮助。

https://github.com/jogeshpi03/omdb-react

答案 1 :(得分:1)

您的代码几乎正确。有一个错误,您可以进行一些改进。

首先让我们看一下useEffect钩子。

useEffect带有两个参数:函数和依赖项列表。第一次渲染组件时,并且当任何依赖项更改时,都会再次执行function参数。

现在,您的依赖项存在一个错误,该错误会导致无限循环。渲染组件后,您可以在useEffect中执行该函数。该函数最终将设置Data。设置Data的值后,将再次执行useEffect函数。它将为Data设置一个新值,这将无限期地再次执行该功能。

解决方法是,如果只希望运行一次,则将依赖项设置为[]。像这样:

  useEffect(() => {
    const Cargar = async () => {
      let respuesta = await fetch("https://api.themoviedb.org/3/discover/movie?api_key=ce322f54257cc9286282b320c5e9b2a0&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1");
      let respuestaJSON = await respuesta.json();
      setData(respuestaJSON);
    };
    Cargar();
  }, []); // <-------- This changed to []

我希望能解决您的问题。

现在,我将提出一些改进建议:

我将Data的初始状态设置为undefined

  const [Data, setData] = useState();

然后像这样在JSX中使用条件

if (!Data) {
  return <div>Loading...</div>
}

return (
  <div>
    {Data.total_results}
  </div>
);

答案 2 :(得分:0)

  

const [Data,setData] = useState([]);

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.eureka.server</groupId>
    <artifactId>eureka-server</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eureka-server</name>
    <description>Eureka Server</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-server</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-server-ui</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!-- <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency> -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

答案 3 :(得分:-1)

让我告诉您一件事,首先,从我的角度来看,您执行此操作的方式是错误的,我已修复错误并在此处进行了堆栈闪电验证,请检查链接Check stackblitz here

const Movie = () => {
  // Declara una nueva variable de estado, que llamaremos "count".
  const [Data, setData] = useState({}); // initialized as object here

  useEffect(() => {
    const Cargar = async () => {
      let respuesta = await fetch("https://api.themoviedb.org/3/discover/movie?api_key=ce322f54257cc9286282b320c5e9b2a0&language=en-US&sort_by=popularity.desc&include_adult=false&include_video=false&page=1");
      let respuestaJSON = await respuesta.json();
      setData(respuestaJSON);
    };
    Cargar();
  }, []);
  return (
    <div>
    <h2>{Data.total_results}</h2>
    // check if Data has result array and then iterates
    {Data.results &&  Data.results.map(movie =>(
      <div key={movie.id}>
        <span>{movie.title}</span>
      </div>
    ))}
    </div>
  );
}

export default Movie;