反应未定义状态

时间:2018-09-25 17:09:21

标签: reactjs

我只是从反应开始,我想从状态显示卡片:

import React, {Component} from 'react';
import personnages from './personnages';
import ChampRecherche from '../components/champrecherche';

class Cards extends Component {
    constructor (props) {
        super(props);
        this.state = {
            dataFromChild:null
        }
    }
    getVal = (dataFromChild) => {
        this.setState({ dataFromChild : dataFromChild })
    }
    listItems = personnages.map((perso) => {
        
        return <li style={{ display: perso.title.indexOf(this.state.dataFromChild) !== -1 ? 'block' : 'none' }} key={perso.id}>{perso.title}</li>  
    });
    render() {
        return(
            <div>
                <ChampRecherche callbackFromParent={this.getVal} />
                <ul>{this.listItems}</ul>
            </div>
        )  
    }
}

export default Cards;

我想从一个状态动态显示块卡或无卡,上面的代码显示错误:

TypeError: Cannot read property 'dataFromChild' of undefined

有人可以解释一下吗?

谢谢。

2 个答案:

答案 0 :(得分:2)

listItems无权访问this.state,因为它没有绑定到类对象。这就是为什么您遇到该错误。我建议您将listItems设为返回您要映射的内容的类函数。像listItems = () => personAges.map...之类的东西希望能解决您的问题。或者,您也可以按照其他答案的建议bind

答案 1 :(得分:0)

您需要绑定。在构造函数中:

 this.listItems = this.listItems.bind(this)

或者当您调用它时:

this.listItems.bind(this)

此外,您需要检查该值,如其他答案所述。

相关问题