javascript - 为什么 map() 返回一个具有未定义值的数组?

标签 javascript arrays reactjs ecmascript-6

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

我的过滤器代码

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;

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

enter image description here

console.log('space is',space) 的输出给出空间是对象 {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
        key = {id}
        space={space}
        propertyType={this.state.propertyType}
        rooms={this.state.rooms}
      />
});

不会返回任何东西。

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

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

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

// { 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)

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

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

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

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

或者将其保留为一个 block ,但添加显式的 return 语句:

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

关于javascript - 为什么 map() 返回一个具有未定义值的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37064027/

相关文章:

javascript - Backbone.js - 如何在模板中使用自定义模型属性?

javascript - 如何将 JSON 变量更改为 3 个具有相同值的变量?

javascript - d3.js 如何向条形图添加线条

reactjs - 为什么在从事件处理程序分配状态时需要设置组件的值?

node.js - 是否可以使用客户端呈现的应用程序和 session 进行身份验证?

javascript - 如何删除 twitter-bootstrap-rails 中多余的 css 和 js 链接

php - 如何找到数组中的最大和最小日期?

c++ - 为什么我不能在 for 循环的第一条语句中包含 2 个变量

mysql - 如何在where条件下检查数组值?

javascript - Redux-form 字段数组,删除函数抛出奇怪的错误