首页 > 解决方案 > Assigning each button it's own individual state count

问题描述

My code below shows my current component design. This is a counter component which is responsible for incrementing a counter for the respective array item and also for adding the clicked item to the cart. I am trying to figure out if there is some way in which I can assign each array item within the items array to its own state count value. Currently, the screen shows four array items, with each one having a button next to it and also a count. When clicking the increment button for any particular item, the state count for all buttons is updated and rendered, which is not what I want. I have tried to assign each button it's own state count in several ways, but haven't been able to figure out the right way. I would like to somehow bind a state count value to each button so that each one has it's individual state count.I would really appreciate if someone can provide some tips or insight as I dont know of a way to isolate the state count for each button and make it unique so that when one value's button is clicked, only the state count for that particular button (located next to the increment button) is updated and not the others.

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0,
      cart: [],
    };
  }

  handleIncrement = (e) => {
    this.setState({
      count: this.state.count + 1,
      cart: [...this.state.cart, e.target.value],
    });
  };

  render() {
    const listItems = this.props.items.map((item) => (
      <li key={item.id}>
        {item.value}
        <button onClick={this.handleIncrement}>+</button>
        {this.state.count}
      </li>
    ));
    return (
      <div>
        {listItems}
      </div>
    );
  }
}

标签: javascriptreactjsreact-props

解决方案


我在这里所做的是删除constructor,更新Counter组件道具,更新有关如何在Example组件中更新购物车的事件,调整Counter组件,对于Cart组件,我添加componentDidMountshouldComponentUpdate确保组件仅在道具listArray更改时重新渲染. 这是代码。

class Example extends React.Component {
    state = {
        cart: [],
        items: [
            { id: 1, value: "L1" },
            { id: 2, value: "L2" },
            { id: 3, value: "L3" },
            { id: 4, value: "L4" }
        ]
    }

    render() {
        const { cart } = this.state

        return (
            <div>
                <h1>List</h1>
                { items.map(
                    ({ id, ...rest }) => (
                        <Counter
                            key={ id }
                            { ...rest }
                            cart={ cart }
                            onAddToCard={ this.handleAddCart }
                        />
                    )
                ) }
            </div>
        )
    }

    handleAddCart = (item) => {
        this.setState(({ items }) => ([ ...items, item ]))
    }
}

class Counter extends React.Component {
    state = {
        count: 0
    }

    handleIncrement = () => {
        this.setState(({ count }) => ({ count: count++ }))
    }
    
    render() {
        const { count } = this.state
        const { cart, value } = this.props

        return (
            <div>
                { value }
                <span>
                    <button onClick={ this.handleIncrement }>+</button>
                    { count }
                </span>
                <Cart listArray={ cart } />
            </div>
        )
    }
}

class Cart extends React.Component {
    state = {
        cart: []
    }

    addTo = () => (
        <div>List: </div>
    )

    componentDidMount() {
        const { cart } = this.props

        this.setState({ cart })
    }

    shouldComponentUpdate({ listArray }) {
        return listArray.length !== this.state.cart.length
    }

    render() {
        return (
            <div>
                <ListFunctions addClick={ this.addTo } />
            </div>
        )
    }
}

const ListFunctions = ({ addClick }) => (
    <div>
        <button onClick={ addClick }>Add To List</button>
    </div>
)


推荐阅读