Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/404.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 反应-Can';t渲染元素数组_Javascript_Reactjs - Fatal编程技术网

Javascript 反应-Can';t渲染元素数组

Javascript 反应-Can';t渲染元素数组,javascript,reactjs,Javascript,Reactjs,我无法使用JSX将对象数组渲染到视图中。它不会加载到屏幕上 我一直在学习React,我可以渲染字符串数组,但不能渲染对象数组 以下是我的组件: import React, { Component } from "react"; export default class PokedexGridComponent extends Component { constructor(props) { super(props); console.log(props); thi

我无法使用JSX将对象数组渲染到视图中。它不会加载到屏幕上

我一直在学习React,我可以渲染字符串数组,但不能渲染对象数组

以下是我的组件:

import React, { Component } from "react";

export default class PokedexGridComponent extends Component {
  constructor(props) {
    super(props);
    console.log(props);

    this.state = {
      pokemons: [],
      all: []
    };
  }

  componentDidMount() {
    this.getPokemons();
  }

  render() {
    return (
      <div>
        <input
          className="btn btn-success btn-sm mb-5"
          type="button"
          onClick={this.getPokemons}
          value="Buscar Pokemons"
        />
        <div>
          {this.state.all.map(data => {
            return <li key={data.key}>{data.name}</li>;
          })}
        </div>
      </div>
    );
  }

  getPokemons = () => {
    var pokemon = [];
    fetch("https://pokeapi.co/api/v2/pokemon?offset=20&limit=964")
      .then(data => {
        return data.json();
      })
      .then(data => {
        data["results"].forEach(data => {
          pokemon.push(data.name.charAt(0).toUpperCase() + data.name.slice(1));
        });

        this.setState({ pokemons: pokemon });
        return this.state.pokemons;
      })
      .then(data => {
        var tmp = [];
        this.state.pokemons.forEach((data, idx) => {
          fetch(`https://pokeapi.co/api/v2/pokemon/${data.toLowerCase()}`)
            .then(data => {
              return data.json();
            })
            .then(data => {
              tmp.push({
                name: data.name,
                image: data.sprites.front_default,
                key: idx
              });
            });
        });

        this.setState({ all: tmp });
        console.log(this.state.all);
      });
  };
}
import React,{Component}来自“React”;
导出默认类PokedexGridComponent扩展组件{
建造师(道具){
超级(道具);
控制台日志(道具);
此.state={
口袋妖怪:[],
全部:[]
};
}
componentDidMount(){
这个。getPokemons();
}
render(){
返回(
{this.state.all.map(数据=>{
返回
  • {data.name}
  • ; })} ); } getPokemons=()=>{ var pokemon=[]; 取回(“https://pokeapi.co/api/v2/pokemon?offset=20&limit=964") 。然后(数据=>{ 返回data.json(); }) 。然后(数据=>{ 数据[“结果”]。forEach(数据=>{ pokemon.push(data.name.charAt(0.toUpperCase()+data.name.slice(1)); }); this.setState({pokemons:pokemon}); 返回this.state.pokemons; }) 。然后(数据=>{ var tmp=[]; this.state.pokemons.forEach((数据,idx)=>{ 取回(`https://pokeapi.co/api/v2/pokemon/${data.toLowerCase()}`) 。然后(数据=>{ 返回data.json(); }) 。然后(数据=>{ 推({ name:data.name, 图像:data.sprites.front\u默认值, 关键字:idx }); }); }); this.setState({all:tmp}); console.log(this.state.all); }); }; }
    控制台返回对象数组,但无法将其映射到render方法


    有人能帮我吗?

    方法是异步的,因此如果在更新状态后需要执行某些操作,则需要使用第二个参数,该参数是更新状态后将执行的函数

    this.setState({ pokemons: pokemon }, function(){
       //perform what you need with the updated
    })
    
    您遇到的另一个问题是在请求到达之前进行更新。您可以收集所有承诺并应用它们。所有

    const requests = []
    pokemons.forEach((data, idx) => {
      const request = fetch(`https://pokeapi.co/api/v2/pokemon/${data.toLowerCase()}`)
        .then((data) => {
          return data.json();
        })
      requests.push(request)
    })
    
    const tmp = [];
    Promise.all(request).then((arrayOfResults) => {
      //Here you have the responses to iterate
      arrayOfResults.forEach((data) => {
        tmp.push({
          name: data.name,
          image: data.sprites.front_default,
          key: idx
        })
      })
      this.setState({all: tmp}, function(){
        //here you can see the state after update
      })
    })
    

    setState
    方法是异步的,因此如果在更新状态后需要执行某些操作,则需要使用第二个参数,该参数是更新状态后将执行的函数

    this.setState({ pokemons: pokemon }, function(){
       //perform what you need with the updated
    })
    
    您遇到的另一个问题是在请求到达之前进行更新。您可以收集所有承诺并应用它们。所有

    const requests = []
    pokemons.forEach((data, idx) => {
      const request = fetch(`https://pokeapi.co/api/v2/pokemon/${data.toLowerCase()}`)
        .then((data) => {
          return data.json();
        })
      requests.push(request)
    })
    
    const tmp = [];
    Promise.all(request).then((arrayOfResults) => {
      //Here you have the responses to iterate
      arrayOfResults.forEach((data) => {
        tmp.push({
          name: data.name,
          image: data.sprites.front_default,
          key: idx
        })
      })
      this.setState({all: tmp}, function(){
        //here you can see the state after update
      })
    })
    

    与Promise.all一起工作,谢谢@SergioEscudero和@Vencovsky

    以下是修改后的代码:

    import React, { Component } from 'react'
    
    export default class PokedexGridComponent extends Component {
    
    constructor(props) {
        super(props);
        this.state = {
            pokemons: [],
            pokeComplete: []
        }
    }
    
    componentDidMount() {
        this.getPokemons();
    }
    
    render() {
        return (
            <div>
                <input className="btn btn-success btn-sm mb-5" type="button" onClick={this.getPokemons} value="Buscar Pokemons" />
                <div>
                   {
                       (this.state.pokeComplete.map((data) => {
                           return (<li>{data.name} | {data.img}</li>)
                       }))
                   }
                </div>
            </div>
        )
    }
    
    getPokemons = () => {
        var pokemons = [];
        fetch("https://pokeapi.co/api/v2/pokemon?offset=20&limit=964")
            .then((data) => {
                return data.json();
            })
            .then((data) => {
                data["results"].forEach((data) => {
                    pokemons.push(data.name)
                })
    
                return pokemons;
            }).then((data) => {
                var arrayReq = [];
                data.forEach((x) => {
                    var req = fetch(`https://pokeapi.co/api/v2/pokemon/${x.toLowerCase()}`)
                        .then((data) => {
                            return data.json();
                        })
                    arrayReq.push(req);
                })
    
                var tmp = [];
                Promise.all(arrayReq)
                    .then((e) => {
                        e.forEach((x) => {
                            tmp.push({
                                name: x.name,
                                img: x.sprites.front_default
                            })
                        })
                    })
                    .then(() => {
                        this.setState({ pokeComplete: tmp });
                    })
            })
        }
    }
    
    import React,{Component}来自“React”
    导出默认类PokedexGridComponent扩展组件{
    建造师(道具){
    超级(道具);
    此.state={
    口袋妖怪:[],
    pokeComplete:[]
    }
    }
    componentDidMount(){
    这个。getPokemons();
    }
    render(){
    返回(
    {
    (this.state.pokeComplete.map((数据)=>{
    返回(
  • {data.name}{data.img}
  • ) })) } ) } getPokemons=()=>{ var口袋妖怪=[]; 取回(“https://pokeapi.co/api/v2/pokemon?offset=20&limit=964") 。然后((数据)=>{ 返回data.json(); }) 。然后((数据)=>{ 数据[“结果”]。forEach((数据)=>{ pokemons.push(data.name) }) 返回口袋妖怪; })。然后((数据)=>{ var arrayReq=[]; data.forEach((x)=>{ var req=fetch(`https://pokeapi.co/api/v2/pokemon/${x.toLowerCase()}`) 。然后((数据)=>{ 返回data.json(); }) 阵列均衡推送(需要); }) var tmp=[]; 承诺。全部(arrayReq) 。然后((e)=>{ e、 forEach((x)=>{ 推({ 姓名:x.name, img:x.sprites.front\u默认值 }) }) }) .然后(()=>{ this.setState({pokeComplete:tmp}); }) }) } }
    承诺一起工作。所有
    ,谢谢@SergioEscudero和@Vencovsky

    以下是修改后的代码:

    import React, { Component } from 'react'
    
    export default class PokedexGridComponent extends Component {
    
    constructor(props) {
        super(props);
        this.state = {
            pokemons: [],
            pokeComplete: []
        }
    }
    
    componentDidMount() {
        this.getPokemons();
    }
    
    render() {
        return (
            <div>
                <input className="btn btn-success btn-sm mb-5" type="button" onClick={this.getPokemons} value="Buscar Pokemons" />
                <div>
                   {
                       (this.state.pokeComplete.map((data) => {
                           return (<li>{data.name} | {data.img}</li>)
                       }))
                   }
                </div>
            </div>
        )
    }
    
    getPokemons = () => {
        var pokemons = [];
        fetch("https://pokeapi.co/api/v2/pokemon?offset=20&limit=964")
            .then((data) => {
                return data.json();
            })
            .then((data) => {
                data["results"].forEach((data) => {
                    pokemons.push(data.name)
                })
    
                return pokemons;
            }).then((data) => {
                var arrayReq = [];
                data.forEach((x) => {
                    var req = fetch(`https://pokeapi.co/api/v2/pokemon/${x.toLowerCase()}`)
                        .then((data) => {
                            return data.json();
                        })
                    arrayReq.push(req);
                })
    
                var tmp = [];
                Promise.all(arrayReq)
                    .then((e) => {
                        e.forEach((x) => {
                            tmp.push({
                                name: x.name,
                                img: x.sprites.front_default
                            })
                        })
                    })
                    .then(() => {
                        this.setState({ pokeComplete: tmp });
                    })
            })
        }
    }
    
    import React,{Component}来自“React”
    导出默认类PokedexGridComponent扩展组件{
    建造师(道具){
    超级(道具);
    此.state={
    口袋妖怪:[],
    pokeComplete:[]
    }
    }
    componentDidMount(){
    这个。getPokemons();
    }
    render(){
    返回(
    {
    (this.state.pokeComplete.map((数据)=>{
    返回(
  • {data.name}{data.img}
  • ) })) } ) } getPokemons=()=>{ var口袋妖怪=[]; 取回(“https://pokeapi.co/api/v2/pokemon?offset=20&limit=964") 。然后((数据)=>{ 返回data.json(); }) 。然后((数据)=>{ 数据[“结果”]。forEach((数据)=>{ pokemons.push(data.name) }) 返回口袋妖怪; })。然后((数据)=>{ var arrayReq=[]; data.forEach((x)=>{ var req=fetch(`https://pokeapi.co/api/v2/pokemon/${x.toLowerCase()}`) 。然后((数据)=>{ 返回data.json(); }) 阵列均衡推送(需要); }) var tmp=[]; 承诺。全部(arrayReq) 。然后((e)=>{ e、 forEach((x)=>{ 推({ 姓名:x.name, 图像:x.sprites.fron