输入搜索过滤器不起作用(React)

时间:2017-01-27 12:27:09

标签: ajax reactjs filter

拥有与React,Redux和AJAX一起使用的组件:

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

        this.state = {
          items: this.props.items || []

        }
      }
      componentDidMount() {
        this.props.IncomeListProfile();

      }
componentWillReceiveProps(nextProps) {
    this.setState({ items: nextProps.items });
}

      filterList(event) {
        var updatedList = this.state.items;
        updatedList = updatedList.filter(function(item) {
          return item.toLowerCase().search(event.target.value.toLowerCase()) !== -1;
        });
        this.setState({items: updatedList}); // now this.state.items has a value
      }

      render() {
        var elems = this.props.items;
        if (typeof elems == 'undefined') {
          elems = [];
        }
        //console.log(elems);
        return (
          <div>
            <table className='table'>
              <thead className='theadstyle'>
                <th>date
                  <input></input>
                </th>

                <th>
                  <input onChange={this.filterList} type='text' placeholder='keyword search'></input>
                </th>
                <th>
                  <input type='text' placeholder='amount search'></input>
                </th>
                <th>amount</th>
                <th>Show archived</th>
              </thead>
              <div className='tbodymar'></div>
              <tbody >
                {elems.map((item) => (

                  <tr key={item.course_id}>
                    <td>{item.created_at}</td>
                    <td>{item.name}</td>
                    <td>{item.remark}</td>
                    <td>{item.income_amount}</td>
                    <td>more options</td>
                  </tr>

                ))}
              </tbody>
            </table>
          </div>
        )

      }
    }

    const mapDispatchToProps = function(dispatch) {
      return {
        IncomeListProfile: () => dispatch(IncomeProfileList())

      }
    }

    const mapStateToProps = function(state) {
      //var mystore = state.toJS()
      var mystore = state.getIn(['incomeProfileList'])['course_list'];

      //console.log(mystored.hh);
      var copy = Object.assign({}, mystore);
      return {items: copy.course_list};

    }
    export default connect(mapStateToProps, mapDispatchToProps)(IncomeProfile);

当我在输入中输入内容时,我得到错误无法读取未定义的属性“状态”,但是console.log显示的是我的状态。过滤器有什么问题?错在哪里?如果我有正确的状态?

1 个答案:

答案 0 :(得分:1)

this.props.items仅在componentDidMount之后填充? 如果是这样,您也想在state中设置项目。您可以使用componentWillReceiveProps方法为您设置新道具。

componentWillReceiveProps(nextProps) {
    this.setState({ items: nextProps.items });
}