0
Bir PubSub olay sistemi kurdum ancak bazı nedenlerden dolayı başarıyla alınmış bir bileşenimin durumunu ayarlamaya çalışırken bir Cannot read property 'items' of undefined
alıyorum.Ayar durumu PubSub ReactJS ve Rayları
this
adresine erişimim yok gibi görünüyor ama neden emin değilim?
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.subscriber)
this.calculateTotals();
}
componentWillUnmount() {
PubSub.unsubscribe(this.token)
}
subscriber(msg, data){
console.log(msg, data) // CONSOLE LOGS CORRECTLY :)
this.setState({
items: this.props.items // RETURNING Cannot read property 'items' of undefined
})
}
.... bottom of file and Render ....
ProductItem Bileşen BasketContainer Bileşeni - yürütüldüğünde yayınlayamaz
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 CORRECTLY
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>
)
}
}
ben Cannot read property 'items' of undefined
almak olabilir neden biliyor musunuz?
Teşekkür olması gereken konu
ile sanırım. Bu hatadan kurtuldu ancak setState hala bileşen/veriyi yeniden oluşturuyor gibi görünmüyor. Bunun neden olabileceği hakkında bir fikrin var mı? :) –