为什么 map() 返回一个带有未定义值的数组? [英] Why does map() return an array with undefined values?

查看:32
本文介绍了为什么 map() 返回一个带有未定义值的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建过滤系统.有两个过滤器菜单.一个是房间数量,另一个是财产类型.我已将 json 文件从 api 加载到空间对象.但是当我尝试将所有这些空间传递给 SpaceFilterResults 组件时,我的空间数组返回为 [undefined, undefined].

我的过滤器代码

class FilterSpace1 扩展 React.Component {构造函数(){极好的();this.handleFormInput = this.handleFormInput.bind(this);this.state = {空间:[],属性类型:0,房间:0}}componentDidMount(){this.loadRoomFromServer();}loadRoomFromServer(){$.ajax({url:'/api/rentals/',数据类型:'json',成功:(数据)=>{console.log('数据',数据);this.setState({space: data.results});console.log('成功',this.state.space);},错误:(xhr,状态,错误)=>{console.error(url, status, err.toString());}});}handleFormInput(属性类型,房间){this.setState({属性类型:属性类型,房间:房间})}使成为() {让空间 = _.map(this.state.space, (space,id) => {console.log('空间是',space);//有一个如下所示的数组<SpaceFilterResults键 = {id}空格={空格}propertyType={this.state.propertyType}房间={this.state.rooms}/>});console.log('space',space);//我得到空间[未定义,未定义]而不是所有的空间返回 (<div className="过滤器"><SpaceFilterMenupropertyType={this.state.propertyType}房间={this.state.rooms}onFormInput={this.handleFormInput}/>{空间}

)}}类 SpaceFilterMenu 扩展了 React.Component {构造函数(){极好的();this.handleChange = this.handleChange.bind(this);}句柄变化(){this.props.onFormInput (this.refs.propertyTypeInput.value,this.refs.roomsInput.value);}使成为() {返回 (<div className="容器"><div className="row"><form className="filter-menu"><label htmlFor="roomsInput">房间数量</label><select id="roomsInput" ref="roomsInput" onChange={this.handleChange}><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option></选择><label htmlFor="propertyTypeInput">propertyType</label><select id="propertyTypeInput" ref="propertyTypeInput" onChange={this.handleChange}><option value="公寓">公寓</option><option value="House">House</option><option value="Shop">Shop</option><option value="Bunglow">Bunglow</option></选择></表单>

);}}类 SpaceFilterResults 扩展了 React.Component {构造函数(){极好的();}使成为() {var 结果 = [];this.props.space.map((space) => {如果(this.props.roomsInput===0){结果.push(<Space space = {space}/>);}else if (space.roomsInput === this.props.roomsInput) {结果.push(<Space space={space}/>);}});this.props.space.map((space) => {如果(this.props.propertyType === 0){结果.push(<Space space={space}/>);}else if (space.propertyType === this.props.propertyType) {结果.push(<Space space={space}/>);}});返回 (<div className="容器"><div className="row"><div className="col-md-4"><div className="filter-results"><ul className="blocks blocks_3up">{结果}

)}}类空间扩展了 React.Component {构造函数(){极好的();}使成为 () {返回 (<li><div className="功能"><div className="feature-hd"><h2 class="hdg hdg_2">{this.props.space.listingName}</h2>

<div className="feature-bd"><p>{this.props.space.room}</p>

<div className="feature-ft"><p>{this.props.space.property}% 个房间</p>

)}}导出默认 FilterSpace1;

我的json文件看起来像(/api/rentals/)

console.log('space is',space) 的输出给出空间是 Object {id: 1, renter: "admin", gallery: Array[2], ownerName: "tushant khatiwada", email: "tushant@gmail.com"...}

我做错了什么?我如何将这些所有空间数据传递给 SpaceFilterResults 组件?

解决方案

这个map回调:

let space = _.map(this.state.space, (space, id) => {<SpaceFilterResults键 = {id}空格={空格}propertyType={this.state.propertyType}房间={this.state.rooms}/>});

不会返回任何东西.

这是另一个不起作用的例子:

let nums = [1, 2, 3].map(x => { x * 2 })

如果箭头函数体是一个块,它不会隐式返回任何东西.

//{ x * 2;} 是一个块所以这不起作用让 nums = [1, 2, 3].map(x => { x * 2; })//x * 2 是一个表达式,所以这是有效的让 nums = [1, 2, 3].map(x => x * 2)

如果在箭头函数中使用 {},则必须还使用 return 语句:

//{ x * 2 } 是一个有返回值的块,所以这是有效的让 nums = [1, 2, 3].map(x => { return x * 2; })

因此,要修复您的代码,请通过删除 {} 使箭头函数体成为表达式:

let space = _.map(this.state.space, (space, id) =><SpaceFilterResults键 = {id}空格={空格}propertyType={this.state.propertyType}房间={this.state.rooms}/>);

或将其保留为块,但添加显式return 语句:

let space = _.map(this.state.space, (space, id) => {返回 (<SpaceFilterResults键 = {id}空格={空格}propertyType={this.state.propertyType}房间={this.state.rooms}/>);});

I am trying to build filter system. There is two filter menu. One is number of room and another is type of property. I have loaded json file from an api to space object. But when i try to pass all those spaces to SpaceFilterResults component my space array returns as [undefined, undefined].

my code for filter

class FilterSpace1 extends React.Component {
  constructor() {
    super();

    this.handleFormInput = this.handleFormInput.bind(this);

    this.state = {
      space:[],
      propertyType: 0,
      rooms: 0
    }
  }

  componentDidMount(){
        this.loadRoomFromServer();
    }

    loadRoomFromServer(){
        $.ajax({
            url:'/api/rentals/',
            dataType:'json',
            success: (data) => {
                console.log('data',data);
                this.setState({space: data.results});
                console.log('success',this.state.space);
              },
              error: (xhr, status, err) => {
                console.error(url, status, err.toString());
              }
            });
    }

  handleFormInput(propertyType, rooms) {
    this.setState({
      propertyType: propertyType,
      rooms: rooms
    })
  }

  render() {
   let space = _.map(this.state.space, (space,id) => {
    console.log('space is',space); // has an array as shown below
      <SpaceFilterResults
            key = {id}
            space={space}
            propertyType={this.state.propertyType}
            rooms={this.state.rooms}
          />
   });
   console.log('space',space); //i get space [undefined, undefined] instead of all the spaces

    return (
      <div className="filter">
        <SpaceFilterMenu
          propertyType={this.state.propertyType}
          rooms={this.state.rooms}
          onFormInput={this.handleFormInput}
        />
        {space}
      </div>
    )
  }
}

 class SpaceFilterMenu extends React.Component {
   constructor() {
     super();
     this.handleChange = this.handleChange.bind(this);
   }

   handleChange() {
     this.props.onFormInput (
       this.refs.propertyTypeInput.value,
       this.refs.roomsInput.value
     );
   }

   render() {
     return (
      <div className="container">
        <div className="row">
           <form className="filter-menu">
             <label htmlFor="roomsInput">Number of rooms</label>
              <select id="roomsInput" ref="roomsInput" onChange={this.handleChange}>
                 <option value="1">1</option>
                 <option value="2">2</option>
                 <option value="3">3</option>
                 <option value="4">4</option>
                 <option value="5">5</option>
                 <option value="6">6</option>
              </select>

             <label htmlFor="propertyTypeInput">propertyType</label>
             <select id="propertyTypeInput" ref="propertyTypeInput" onChange={this.handleChange}>
               <option value="Appartment">Appartment</option>
               <option value="House">House</option>
               <option value="Shop">Shop</option>
               <option value="Bunglow">Bunglow</option>
             </select>
           </form>
          </div>
      </div>
     );
   }
 }

class SpaceFilterResults extends React.Component {
  constructor() {
    super();
  }

  render() {
    var results = [];

   this.props.space.map((space) => {
    if(this.props.roomsInput===0){
      results.push(<Space space = {space} />);
    }
    else if (space.roomsInput === this.props.roomsInput) {
        results.push(<Space space={space} />);
      }
   });

    this.props.space.map((space) => {
      if (this.props.propertyType === 0 ) {
        results.push(<Space space={space} />);
      }
      else if (space.propertyType === this.props.propertyType) {
        results.push(<Space space={space} />);
      }
    });

    return (
      <div className="container">
        <div className="row">
          <div className="col-md-4">
             <div className="filter-results">
                <ul className="blocks blocks_3up">
                  {results}
                </ul>
              </div>
          </div>
        </div>
      </div>

    )
  }
}

class Space extends React.Component {
  constructor () {
    super();
  }

  render () {
    return (
      <li>
        <div className="feature">
          <div className="feature-hd">
            <h2 class="hdg hdg_2">{this.props.space.listingName}</h2>
          </div>
          <div className="feature-bd">
            <p>{this.props.space.room}</p>
          </div>
          <div className="feature-ft">
            <p>{this.props.space.property}% rooms</p>
          </div>
        </div>
      </li>
    )
  }
}                            

export default FilterSpace1;

my json file looks like(/api/rentals/)

the output of console.log('space is',space) gives space is Object {id: 1, renter: "admin", gallery: Array[2], ownerName: "tushant khatiwada", email: "tushant@gmail.com"…}

What have i done wrong? How can i pass these all space data to SpaceFilterResults component?

解决方案

This map callback:

let space = _.map(this.state.space, (space, id) => {
  <SpaceFilterResults
        key = {id}
        space={space}
        propertyType={this.state.propertyType}
        rooms={this.state.rooms}
      />
});

will not return anything.

Here is another example that doesn’t work:

let nums = [1, 2, 3].map(x => { x * 2 })

If an arrow function body is a block, it doesn’t implicitly return anything.

// { x * 2; } is a block so this doesn’t work
let nums = [1, 2, 3].map(x => { x * 2; })

// x * 2 is an expression so this works
let nums = [1, 2, 3].map(x => x * 2)

If you use { and } inside an arrow function, you must also use a return statement:

// { x * 2 } is a block with a return so this works
let nums = [1, 2, 3].map(x => { return x * 2; })

So to fix your code, either make the arrow function body an expression by removing { and }:

let space = _.map(this.state.space, (space, id) =>
  <SpaceFilterResults
        key = {id}
        space={space}
        propertyType={this.state.propertyType}
        rooms={this.state.rooms}
      />
);

or keep it as a block but add an explicit return statement:

let space = _.map(this.state.space, (space, id) => {
  return (
    <SpaceFilterResults
        key = {id}
        space={space}
        propertyType={this.state.propertyType}
        rooms={this.state.rooms}
    />
  );
});

这篇关于为什么 map() 返回一个带有未定义值的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆