为什么我的反应组件没有更新?

时间:2017-01-09 12:18:33

标签: reactjs redux conditional components updates

我有一个简单的<div id="44332211">33-ab-v4</div> 组件,我想在没有项目的情况下显示“您的购物车是空的”消息。

Cart

我的import React, { Component } from 'react' import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import * as CartActions from '../actions/cart' import Shelf from './Shelf' import EmptyCart from './EmptyCart' /* This is a container component */ class Cart extends Component { constructor(props) { super(props) this.state = { itemQuantity: props.cart.length } } render() { const CartItems = this.props.cart.map( (item, idx) =><li key={idx}>{item.name} - ${item.price}</li> ) const isCartEmpty = () => this.state.itemQuantity === 0 console.log("is cart empty? ", isCartEmpty(), "cart item quantity ", this.state.itemQuantity) return( <div className="Cart"> <Shelf addItem={this.props.action.addToCart} /> <h2>Cart Items</h2> <ol> { isCartEmpty() ? <EmptyCart/> : {CartItems} } </ol> </div> ) } } function mapStateToProps(state, prop) { return { cart: state.cart } } function mapDispatchToProps(dispatch) { return { action: bindActionCreators(CartActions, dispatch) } } export default connect(mapStateToProps, mapDispatchToProps)(Cart) 组件如下所示:

Shelf

购物车减速机:

import React, { Component } from 'react';

class Shelf extends Component {
  constructor(props) {
    super(props)

    this.addItemToCart = this.addItemToCart.bind(this)

    this.state = {
      shelfItems: [
        { "name": 'shampoo', "price": 23 },
        { "name": 'chocolate', "price": 15 },
        { "name": 'yogurt', "price": 10 }
      ]
    }
  }

  addItemToCart(item){
    this.props.addItem(item)
  }

  render() {
    const shelfItems = this.state.shelfItems.map((item, idx) => {
      return <li key={idx}><button onClick={()=>this.addItemToCart(item)}>[+]</button>{item.name} - ${item.price}</li>
    })
    return(
      <div>
        <h2>Shelf</h2>
        <ul>
          {shelfItems}
        </ul>
      </div>
    )
  }
}
export default Shelf

export default(state = [], payload) => { switch (payload.type) { case 'add': return [...state, payload.item] default: return state } } 行动:

addToCart

显示空消息,但添加项目时列表不会更新。我究竟做错了什么?如果我删除条件并只渲染export const addToCart = (item) => { return { type: 'add', item } }

,代码就可以正常工作

1 个答案:

答案 0 :(得分:1)

这是因为你只设置了初始状态。添加项目时,不设置新状态。如果使用redux,则不需要本地状态。

试试这个:

class Cart extends Component {

  constructor(props) {
    super(props)
    this.state = {}
  }

  render() {
    const CartItems = this.props.cart.map(
      (item, idx) =><li key={idx}>{item.name} - ${item.price}</li>
    )

    const isCartEmpty = CartItems.length === 0

    return(
      <div className="Cart">
        <Shelf addItem={this.props.action.addToCart} />
        <h2>Cart Items</h2>
        <ol>
         {isCartEmpty ? <li>Your Cart is Empty</li> : CartItems}
        </ol>
      </div>
    )
  }
}