【问题标题】:ReactJs component dynamic data is not prepared into a listReactJs 组件动态数据未准备成列表
【发布时间】:2020-05-24 21:30:21
【问题描述】:

我有一个 ReactJs 组件,它从 api 获取数据并将其传递给 Slider 组件。似乎当我使用.map() 映射响应数据时,它不起作用,但如果我直接使用通过道具传递的组件中的数组索引调用数据,它会起作用。

例如我下面有两个组件,定义如下。

这是我将向其传递数据的内部组件。

import React, { Component } from 'react';
import parse from 'html-react-parser';

class HeroAreaSlid extends Component {
  render() {
    return (
      <>
        <li style={{backgroundImage:`url(${this.props.data && this.props.data.backgroundImg !== undefined && this.props.data.backgroundImg})`}}>
          <div className="overlay"></div>
          <div className="container-fluid">
            <div className="row">
              <div className="col-md-6 col-md-offset-3 col-md-pull-3 col-sm-12 col-xs-12 js-fullheight slider-text">
                <div className="slider-text-inner js-fullheight">
                  <div className="desc">
                    <h1>
                    {
                      this.props.data && this.props.data.headerLine !== undefined &&
                      parse(this.props.data.headerLine)
                    }
                    </h1>
                    <p><a className="btn btn-primary btn-learn" href={this.props.data && this.props.data.link !== undefined && this.props.data.link} target="_blank" rel="noopener noreferrer">
                    {
                      this.props.data && this.props.data.text !== undefined &&
                      parse(this.props.data.text)
                    }
                    <i className={this.props.data && this.props.data.icon !== undefined && this.props.data.icon}></i></a></p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </li> 
      </>
    );
  }
}
export default HeroAreaSlid;

我从这个组件中调用它。

import React, { Component } from 'react'; 
import axios from 'axios'; 

import HeroAreaSlid from './hero-area_slide'

class HeroArea extends Component {
  constructor(props){
        super(props)

        this.state = {
      heroarea_: []
    }
  }

  componentDidMount(){
        axios.get("https://sym-api-dev.herokuapp.com/sym-api/me/heroarea")
        .then(response =>{
      this.setState({heroarea_: response.data});
      this.setState({flag: true});
        })
        .catch(error =>{
            console.log(error);
    })
  } 

  render() {
    let {heroarea_} = this.state; 
    return (
      <>
        <section id="sym-hero" className="js-fullheight" data-section="home">
          <div className="flexslider js-fullheight">
            <ul className="slides">
              <HeroAreaSlid
                 data = {heroarea_[0]}
              />
              <HeroAreaSlid
                data = {heroarea_[1]}
              />
              <HeroAreaSlid
                data = {heroarea_[2]}
              />
            </ul>
          </div>
        </section>
      </>
    );
  }
}
export default HeroArea;

上面,如果我调用 HeroAreaSlid 三次,那么它可以工作,但如果我用下面的代码更改该块,它就不会。

{
   heroarea_.map(heroarea_inner => {
   <HeroAreaSlid
    data = {heroarea_[0]}
   />
   })
}

它不工作。请帮我让它动态化。

【问题讨论】:

    标签: javascript react-native dynamic react-redux react-router


    【解决方案1】:

    我已经弄清楚解决方案就像在渲染数据之前我已经在渲染中传递虚拟数据以创建该组件,当数据到来时,它将从 api 传递实际数据

    渲染代码如下

     render() {
            let {heroarea_} = this.state; 
            console.log("heroarea_1 :: "+heroarea_);
    
            const numbers = [1, 2, 3];
            const doubled = numbers.map((number) => number * 2);
            return (
              <>
                <section id="sym-hero" className="js-fullheight" data-section="home">
                  <div className="flexslider js-fullheight">
                    <ul className="slides">
                    {console.log("heroarea_2 :: "+heroarea_)}
                    {!heroarea_.length && this.setState({heroarea_:doubled})}
                    {console.log("heroarea_3 :: "+heroarea_)}
                    {
                      heroarea_.map(heroarea_inner => 
                        <HeroAreaSlid data = {heroarea_inner}/>
                      )
                    }
                    </ul>
                  </div>
                </section>
              </>
            );
          }
    

    【讨论】:

      【解决方案2】:

      TLDR:

      可能的错误:当您映射返回的 api 数据时,您没有返回一个组件,并且总是试图返回第一个。您应该返回一个 JSX 组件。喜欢...

      // Note: You should add a unique key to your mapped data
      {heroarea_.map(heroarea_inner => (
        <HeroAreaSlid key={heroarea_inner.headerLine} data={heroarea_inner} />
      ))}
      
      

      在这里观看CodeSandbox for your Code 的直播


      @Mahesh,当你映射一个数组时,你应该总是从你的回调函数中返回一些东西。

      • React 需要一个元素来渲染,但是你的箭头函数没有返回任何东西。请参阅评论 1

      • 在数组上映射时,回调会传递数组中该项目的(元素,索引)。因此,您将迭代中的元素指定为heroarea_inner,但您不会在任何地方使用它,而是每次使用heroarea_[0] 直接调用数组中的第一项。所有列表项最终将与第一个相同。请参阅评论 2

      • 为了重新渲染时的性能,最好将唯一的key 传递给相似组件列表中的项目。请参阅 评论 3

      {
         heroarea_.map(heroarea_inner => { 
         // 1. This component is not being returned.
         <HeroAreaSlid
           data = {heroarea_[0]} // 2. This always returns the 1st item. Use heroarea_inner
           key={unqueItem} // 3. Use a unique item in you heroarea_inner 
         />
         })
      }
      

      您可以阅读 .map() here 并了解它如何用于渲染反应列表 here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-21
        • 2020-03-23
        • 1970-01-01
        • 1970-01-01
        • 2014-12-16
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        相关资源
        最近更新 更多