簡體   English   中英

反應:在子組件函數中未定義父組件的“ this.state”

[英]React: 'this.state' of parent component is undefined inside a child component function

我正在用ReactJS開發一個在線訂購表格。 現在,我在瀏覽器控制台中收到消息,例如“ this.state”在組件函數中未定義……這是怎么回事? 如何避免該問題? 我沒有在官方文檔中找到任何線索。

class Service extends React.Component {
    constructor(props){
        super(props);
        this.state  = {active:      false,}
    }
    clickHandler(){
        let active = !this.state.active;
        this.setState({active: active});
        this.props.addTotal((active == true ? this.props.price : -this.props.price));
    }
    render(){
        return(
            <p className={this.state.active ? 'active' : ''} onClick={() => this.clickHandler()}>
                {this.props.name} <b>${this.props.price.toFixed(2)}</b>
            </p>
        );  
    }
};

class OrderForm extends React.Component {
    constructor(){
        super();
        this.state  = { total:  0,}
    }   
    addTotal(price){
        this.setState({total: this.state.total + price});
    }
    serviceList(){
        var self    =   this;
        //Iteration with map method
        const serviceMapIterator = this.props.services.map(function(item, i, arr){
                return (<Service    key     =   {i.toString()} 
                                    name    =   {item.name} 
                                    price   =   {item.price} 
                                    active  =   {item.active} 
                                    addTotal=   {self.addTotal} >
                        </Service>);
        });
        return serviceMapIterator;
    }
    render(){
        let service =   this.serviceList();
        return(
            <div>
                {service}
                <p id={'total'}>Total <b>${this.state.total.toFixed(2)}</b></p>
            </div>
        );
    }
};
var services = [
    { name: 'Web Development',  price: 300 },
    { name: 'Design', price: 400 }
];

我該如何更改? 問題是什么?

您可以從Service(子類)調用OrderForm(父類)中定義的addTotal()方法。 您需要addTotal有權訪問父類的“狀態”。 因此,您將通過添加帶有.bind(this)的行來更改針對Constructor()的代碼:

    constructor(){
        super();
        this.state  = { total:  0,};
        this.addTotal = this.addTotal.bind(this);
    }

或對於serviceList()方法,通過在javascript方法的.map()之后添加.bind(this)。 請看下面:

    serviceList(){
        var self    =   this;
        //Iteration with map method
        const serviceMapIterator = this.props.services.map(function(item, i, arr){
                return (<Service    key     =   {i.toString()} 
                                    name    =   {item.name} 
                                    price   =   {item.price} 
                                    active  =   {item.active} 
                                    addTotal=   {self.addTotal} >
                        </Service>);
        }.bind(this));
        return serviceMapIterator;
    }

調用addTotal時,這不引用OrderForm組件的上下文。 您應該在構造函數中綁定如下的addTotal函數:

constructor() {
  ...
  this.addTotal = this.addTotal.bind(this)
}

您的addTotal函數如下所示:

addTotal(price){
        this.setState({total: this.state.total + price});
}

根據DOCS

你不應該寫

this.setState({total: this.state.total + price});

您應該使用setState的第二種形式,該形式接受一個回調函數,該回調函數接收previousState和previousProps作為參數。

addTotal(price) {
  this.setState((prevState, previousProps) => ({
    counter: prevState.total + price
  }));
}

clickHandler函數中需要進行類似的更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM