Запуск массива объектов вне функции рендеринга - PullRequest
0 голосов
/ 22 сентября 2019

Либо не удается скомпилировать определяющие переменные внутри componentDidMount.Я сделал кучу десятков других способов.Кажется, ни один из них не работает для моего конкретного кода.Я думаю, что чтение лучше, чем пытаться объяснить.

import React from 'react';
import { connect } from './api';
import './App.css';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      giphy: []
    }
  }

  componentDidMount(){
    connect(message => {
      this.setState({
        giphy: message
      })
    });
    var Items = this.state.giphy.map(function(gif){ // items is not defined.
      return <li>{gif}</li>;
    })
  }

  render () {
      return (
        <div className=".App-logo">
            <ul>
              { Items } // I wanted to show all items inside the array of objects.
            </ul>

            <ul className=".App-logo"> 
            // the following method works. We need to make sure to check for this conditions or wont work
              {this.state.giphy && this.state.giphy.length > 0   &&
                <img src={ this.state.giphy[2].images.original.url}
                alt="giphy.com animations"/>}
            </ul>
      </div>
    )
  }
}

Если я уберу предметы, то в состоянии 2-го предмета.Можете помочь показать все в состоянии?

enter image description here

Ответы [ 2 ]

2 голосов
/ 22 сентября 2019

Вместо создания переменной в componentDidMount, которую нельзя использовать внутри метода render, вы можете напрямую map указать ваше состояние в методе render.

<ul>
   //This will show only `bitly_gif_url`
   {Array.isArray(this.state.giphy) && this.state.giphy.map(gif => <li>{gif.bitly_gif_url}</li>) } 
</ul>

Примечание: Ваш массив giphy содержит количество объектов.Из каждого объекта, который я показал только bitly_gif_url, используя {gif.bitly_gif_url}, если вам нужно показать какой-либо другой элемент из вашего объекта, вы можете изменить его ключ.

Вы можете также показать несколько элементов одновременно,

<ul>
   //This will show `bitly_gif_url` and `embed_url` at a time
   {Array.isArray(this.state.giphy) && this.state.giphy.map(gif => <li>{gif.bitly_gif_url} {gif.embed_url}</li>) } 
</ul>
0 голосов
/ 22 сентября 2019

Поскольку вы определили Items внутри функции componentDidMount, она имеет функциональную область и не будет доступна внутри функции рендеринга, поэтому вы можете возвращать элементы из функции.Теперь ваш код будет выглядеть примерно так:

import React from 'react';
import { connect } from './api';
import './App.css';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      giphy: []
    }

  }

  componentDidMount(){
    connect(message => {
      this.setState({
        giphy: message
      })
    });
  }

  getItems() {
    return this.state.giphy.map(function(gif){
      return <li>{gif}</li>;
    })
  }

  render () {
      return (
        <div className=".App-logo">
            <ul>
              { this.getItems() } // I wanted to show all items inside the array of objects.
            </ul>

            <ul className=".App-logo"> 
            // the following method works. We need to make sure to check for this conditions or wont work
              {this.state.giphy && this.state.giphy.length > 0   &&
                <img src={ this.state.giphy[2].images.original.url}
                alt="giphy.com animations"/>}
            </ul>
      </div>
    )
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...