【问题标题】:Mapping array returns undefined values映射数组返回未定义的值
【发布时间】:2019-09-18 11:50:50
【问题描述】:

我正在映射一个名为 tours 的数组

   export const tourData = [
  {
    id: 1,
    city: "new york",
    img: "./img/newyork.jpeg",
    name: "new york bridge tour",
    info:
      "Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel,repellendus!"
  },

如下图

 state={
    tours: tourData
} 
 render(){
    const {tours} = this.state;

    return(
        <section className="tourlist">
          {tours.map(tour => {
              return (
                  <Tour key={tour.id} tour={tour} removeTour={this.removeTour}/>
              )
          })}
        </section>
    )
}

然后我将游览作为道具传递给游览组件。

const {id , city , img, name, info} = this.props.tour;
    const {removeTour} = this.props;

webapp 运行良好,但是当我对 Tour 组件进行测试并将值作为道具传递时

 const props ={
            id : 1,
            city: 'Test City ',
            img: 'Test img',
            name: 'Test name',
            info: 'Test Info'
        }

我得到类似的错误

无法读取未定义的属性“id”

但 web 应用程序运行良好。 在这方面需要一些帮助,提前致谢

【问题讨论】:

  • tours 变量的值是什么样的?
  • 你的tours变量在你初始化之前被调用了吗?
  • @P4uB0rd4 我叫它
  • 名为 tours 的数组 看起来像一个对象
  • @TheMaster 实际上是一个数组

标签: javascript arrays reactjs mapping


【解决方案1】:

在你的测试中将值传递给 Tour 组件的 props 时,你应该做这样的事情

const props = {
  tour: {
    id : 1,
    city: 'Test City',
    img: 'Test img',
    name: 'Test name',
    info: 'Test Info'
  }
};

因为在您的 Tour 组件内部,它是从 this.props.tour 读取的。

【讨论】:

  • 很高兴为您提供帮助..!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-29
  • 2020-10-31
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多