反应过滤器“状态”未定义

时间:2017-10-08 19:02:02

标签: reactjs jsx axios

所以我开始使用reactjs并且我设法循环浏览一些XML数据,但是在向其中添加搜索/过滤器时遇到了问题。

到目前为止,这是我的代码:

import React, { Component } from 'react';
import XMLMapping from 'xml-mapping';
import axios from 'axios';

class Guests extends Component {
  constructor(props) {
    super(props);
    this.state = {
        guests: [],
        search: 'Search Guests'
    };
 }

componentDidMount() {
  axios.get('http://localhost:8080/guestlist.xml')
  .then(res => {
    const xml = XMLMapping.load(res.data);
    var guests  = XMLMapping.tojson(xml);
    this.setState({guests: guests});
    //console.log(guests);
    return guests;
  });
}
updateSearch(event) {
  this.setState({
    // Limit to 10 characters only for search
    search: event.target.value.substr(0, 10)
  });
  //    console.log(this.state.search); // this will show the previous value of state.
}
  render() {
    function mapObject(object, callback) {
      return Object.keys(object).map(function (key) {
        return callback(key, object[key]);
      });
    }
    const firstname = mapObject(this.state.guests, function (key, value) {
      return <div key={key}>
        {value.record
        .map((item,index) => {
          //console.log(index)
          return <div className="columns" key={index}>
            <div className="column" key={index}>{item.first_name.$t} {item.last_name.$t}</div> 
            <div className="column" >{item.company.$t}</div>
          </div>;
        })}
        </div>
      });
      let filteredGuests = mapObject(this.state.guests, function (key, value) {
        value.record.filter(
          (contact) => {
            return contact.first_name.$t.indexOf(this.state.search) !== -1;
            //console.log(this.state.search)
          }
        );
      });
    return (
      <div>
          <div className="container">
                <section className="section">
                    <h1 className="title">Guests attending Event A</h1> <input className="text" type="text" value={this.state.search} onChange={this.updateSearch.bind(this)} /> 
                    <div className="columns"><div className="column">Name</div><div className="column">Company</div></div>             
                          {firstname}
                </section>
            </div>
        </div>
    );
  }
}

export default Guests;

但它似乎抛出错误TypeError:无法读取未定义的属性'state'

这是return contact.first_name.$t.indexOf(this.state.search) !== -1;

任何建议或反馈都会很感激!

1 个答案:

答案 0 :(得分:2)

正如 Prakash sharma 所写,您使用了错误的函数上下文。

尝试使用箭头功能替换function

let filteredGuests = mapObject(this.state.guests, (key, value) => {
  value.record.filter(
    (contact) => {
      return contact.first_name.$t.indexOf(this.state.search) !== -1;
      //console.log(this.state.search)
    }
  );
})