Reactjs代码错误 - 无法读取未定义的属性'renderCat'

时间:2017-07-12 07:30:57

标签: reactjs

我的代码是:

import 'babel-polyfill';

import React from 'react';

import ReactDOM from "react-dom";


 class SearchTree extends React.Component{

  constructor(props){

      super(props);
      this.state = {searchString: ''};
   }


   handleChange(e){

    this.setState({
            searchString: e.target.value.trim().toLowerCase(),
             visible: !this.state.visible
        });
    }
   isMatch(e,searchString){

        return e.Name.toLowerCase().match(searchString)
    }
   nestingSerch(e,searchString){

        //recursive searching nesting
        return this.isMatch(e,searchString) || (e.subcats.length && e.subcats.some(e=>this.nestingSerch(e,searchString)));
    }

    nestingSerch(e,searchString){
        //recursive searching nesting
        return this.isMatch(e,searchString) || (e.subcats.length && e.subcats.some(e=>this.nestingSerch(e,searchString)));
    }
    renderCat(cat){
        //recursive rendering
        return (
            <li key={cat.Id}> {cat.Name}
                {(cat.subcats && cat.subcats.length) ? <ul>{cat.subcats.map(this.renderCat)}</ul>:""}
            </li>);
    }

    render() {

        let {items} = this.props;
        let {searchString} = this.state;

        if (searchString.length) {
            items = items.filter(e=>this.nestingSerch(e,searchString))
            console.log(items);
        };

        //nesting, adding to cattegories their subcatigories
        items.forEach(e=>e.subcats=items.filter(el=>el.ParentId==e.Id));
        //filter root categories
        items=items.filter(e=>e.ParentId==0);

        //filter root categories
        return (
            <div>
                <input onChange={this.handleChange} placeholder="Type here" type="text" style={{"width" : "50%",borderColor: "#38c",height:"20"}}  value={this.state.searchString}/>
                <ul>{items.map(this.renderCat)}</ul>
            </div>
        );
    }
}

 export default SearchTree;

这里我得到-Cannot读取属性'renderCat'的未定义错误。请帮帮我

2 个答案:

答案 0 :(得分:0)

“map”函数应该得到一个函数,其中(item,index)或just(item)作为参数。例如: items.map((curr)=&gt; {return {curr.name}}) 对于这个例子来说它是递归的并不重要,因为它返回evetually nest li-&gt; ul元素,它们都在一个大的li元素之下。

答案 1 :(得分:0)

这应该有帮助

const { renderCat } = this;

并作为回报

<ul>{items.map((item) => { return renderCat(item) })}</ul>