0

我有一个带有两个 reactJS 组件(不是父/子)的 rails 应用程序,它们当前通过全局事件 Pub/Sub 系统进行通信。

但是,当我跑步时,this.setState({ items: this.props.items })我收到了消息Cannot read property 'items' of undefined

人们可以就我为什么会收到此错误提供任何帮助将不胜感激。

我的基本设置是:

BasketContainer - 订阅了两个事件

class BasketContainer extends React.Component{

constructor() {
    super()
    this.state = {
        items: [],
        subTotal: 0,
        totalPrice: 0,
        deliveryPrice: 0
    }
}
componentWillMount() {
    this.setState( {
        items: this.props.items,
    })
}
componentDidMount() {
    this.token = PubSub.subscribe('ADD_BASKET', this.handleUpdate)
    this.token = PubSub.subscribe('REMOVE_ITEM', this.handleUpdate)
    this.calculateTotals();
}

componentWillUnmount() {
PubSub.unsubscribe(this.token)
}

handleUpdate(msg, data){
    console.log(msg)
    this.setState({
        items:this.props.items // ERROR MESSAGE - Cannot read property 'items' of undefined
    })
}
.... Rest of file

ProductItem - 添加到购物篮事件发布者

class ProductItem extends React.Component{

constructor() {
    super()

    this.state = { 
        name: '',
        price: 0,
        code: '',
        id: ''
    }
}

componentWillMount() {
    this.setState({
        name: this.props.data.name,
        price: this.props.data.price,
        code: this.props.data.code,
        id: this.props.data.id
    })
}

addtoBasket() {
    $.ajax({
        type: "POST",
        url: "/items",
        dataType: "json",
        data: {
            item: {
                name: this.state.name,
                price: this.state.price,
                code: this.state.code
            }
        },
        success: function(data) {
            PubSub.publish('ADD_BASKET', data); // THIS WORKS FINE
            console.log("success");
        },
        error: function () {
            console.log("error");
        }
    })
}

render(){
    let productName = this.props.data.name
    let productPrice = this.props.data.price
    let productCode = this.props.data.code
    let productImg = this.props.data.image_url

    return (
        <div className="col-xs-12 col-sm-4 product">
            <img src={productImg}/>
            <h3 className="text-center">{productName}</h3>
            <h5 className="text-center">£{productPrice}</h5>
            <div className="text-center">
                <button onClick={this.addtoBasket.bind(this)} className="btn btn-primary">Add to Basket</button>
            </div>
        </div>
    )
}
}

BasketItem - 从篮子发布者中删除

class BasketItem extends React.Component{

constructor(props) {
    super()

    this.state = { 
        name: '',
        price: 0,
        code: '',
        id: '',
        quantity: 1,
    }
}

componentWillMount() {
    this.setState({
        name: this.props.data.name,
        price: this.props.data.price,
        code: this.props.data.code,
        id: this.props.data.id,
    })
}

deleteItem() {
    let finalUrl = '/items/' + this.state.id;
    $.ajax({
        type: "DELETE",
        url: finalUrl,
        dataType: "json",
        success: function(data) {
            PubSub.publish('REMOVE_ITEM', data); // THIS WORKS FINE
        },
        error: function () {
            console.log("error");
        }
    })
}   

render(){
    let itemName = this.props.data.name
    let itemCode = this.props.data.code
    let itemQuantity = 1
    let itemPrice = (this.props.data.price * itemQuantity).toFixed(2)
    const itemId = this.props.data.id

    return(
        <tr>
            <td>{itemName}</td>
            <td>{itemCode}</td>
            <td>{itemQuantity}</td>
            <td><button className="btn btn-warning" onClick={this.deleteItem.bind(this)}>Remove</button></td>
            <td>£{itemPrice}</td>
        </tr>
    )
}
}
4

2 回答 2

1

我认为问题在于以下代码行

this.token = PubSub.subscribe('ADD_BASKET', this.handleUpdate)

您作为参数传递的函数需要与“this”绑定

this.token = PubSub.subscribe('ADD_BASKET', this.handleUpdate.bind(this))

与 REMOVE_ITEM 操作相同。那么应该很好去:)

于 2016-04-11T13:14:20.773 回答
0

您应该将属性从其父类传递itemsBasketContainer 。这就是你收到错误的原因Cannot read property 'items' of undefined.

更新:你提到错误的那一行,你得到的错误是因为错误的引用this

尝试类似:

handleUpdate(msg, data){
    var self = this;
    this.setState({
        items: self.props.items // Here get props from self variable
    })
}
于 2016-04-11T13:23:09.320 回答