在reactjs onclick事件中更新了所有按钮

时间:2018-09-16 10:26:34

标签: javascript reactjs javascript-events event-handling

单击一个按钮将更新所有按钮,但是我想更改该特定单击按钮的状态。请检查下面的图像链接和代码。

import React from 'react';
import './MenuCard.css';

class MenuCard extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        showButton: false,
        hideButton: true,
        aValue: 1,
        breads: [],
        category: [],
        ids: 1,
        btnVal: 'Add'

    };
}

onKeyCheck = (e) => {
    this.state.breads.map(filt => {
        if (filt.id === e.target.id) {
            console.log(e.target.id + ' and ' + filt.id)
            return (this.setState({showButton: !this.state.showButton, hideButton: !this.state.hideButton}));
        }
    })
}

onShowButton = () => {
    this.setState({showButton: !this.state.showButton, hideButton: !this.state.hideButton})
}
onValueIncrease = () => {
    this.setState({aValue: this.state.aValue + 1});
}

onValueDecrease = () => {
    this.setState({aValue: this.state.aValue - 1});
}

componentDidMount() {
    fetch('http://localhost:3000/menu/food_category', {
        method: 'get',
        headers: {'content-type': 'application/json'}
    })
        .then(response => response.json())
        .then(menudata => {
            this.setState({category: menudata.menu_type})
            console.log(this.state.category)
        })

    fetch('http://localhost:3000/menu', {
        method: 'get',
        headers: {'content-type': 'application/json'}
    })
        .then(response => response.json())
        .then(menudata => {
            this.setState({breads: menudata  })
        })
}


render() {

    return (
        <div>
            {this.state.category.map(types => {
                return (<div>
                    <div className="menu-head">{types}</div>
                    < div className="container-menu">
                        {this.state.breads.map((d, id)=> {
                            if (d.category === types) {
                                return (
                                    <div>
                                        <div className="content" key={id} id={d.id}>
                                            <div className="items"> {d.item_name}</div>
                                            <div className="prices"> {d.price} Rs.</div>
                                            {this.state.showButton ?
                                                <div>
                                                    <button
                                                        className="grp-btn-minus"
                                                        onClick={this.state.aValue <= 1 ?
                                                            () => this.onShowButton() :
                                                            () => this.onValueDecrease()}>-
                                                    </button>
                                                    <input className="grp-btn-text" type="text"
                                                           value={this.state.aValue} readOnly/>
                                                    <button id={d.id}
                                                            className="grp-btn-plus"
                                                            onClick={() => this.onValueIncrease()}>+
                                                    </button>
                                                </div> :
                                                <button id={d.id} key={id}
                                                        onClick={ this.onKeyCheck}
                                                        className="add-menu-btn">
                                                    add
                                                </button>
                                            }
                                        </div>
                                    </div>
                                )
                            }
                        })}
                    </div>
                </div>)
            })}
        </div>
    )
}
}

export default MenuCard;

This is the first image of multiple rendering of component Add buttons

Here is the problem that all buttons get updated on single click

2 个答案:

答案 0 :(得分:0)

似乎所有按钮都共享相同的状态。您可以尝试将按钮分解为自己的组件,然后将按钮需要的状态移到该组件中。这样,当您单击一个按钮时,一个特定按钮的状态将被更新,而不是包含所有按钮的父组件的状态。

答案 1 :(得分:0)

您正在使用array项,但在处理程序中引用的是单个共享值。实际上,您正在使用一些共享值:showButton, hideButton, aValue),2/3不必要;)

首先-每个项目的aValue应该存储在结构中-arrayobject。可能是order = {}-具有id键控属性的对象,其值的值如下所示:

order = {
  'masala_id': 1,
  'kebab_id' : 2
}

事件处理程序(用于“添加”)应检查所选对象的id是否已存在于订购对象中(作为属性名称)并更新金额(+/-)或使用1创建新产品值(并在减少量= 0时删除属性)。

在实践中,order还应包含一个price-看起来就像是重复数据,但更容易计算总订单价值。

order = {
  'masala_id': {
      'amount': 1,
      'price': 20,
    },
  'kebab_id' : {
      'amount': 2,
      'price': 180,
    }
}

Item不必是组件,但维护起来容易,保持可读性等。

这样,我们可以简单地传递已订购的数量并有条件地渲染按钮:

<Product id={d.id}
  name={d.item_name}
  price={d.price}
  amount={order[d.id] ? order[d.id].amount : 0 }
  amountHandler={this.changeAmountHandler}
/>

产品应稍作改进和简化(例如,key最前面需要div

class Product extends React.Component {
  render () {
    const (id, name, price, amount, amountHandler} = this.props;
    const showIncrease = !!amount; // boolean, it also means "don't show add button"
    return (
      <div key={id} >
        <div className="content">
          <div className="items">{name}</div>
          <div className="prices">{price} Rs.</div>
          {showIncrease ?
            <div>
              <button
                className="grp-btn-minus"
                onClick={(e) => { amountHandler(e, id, -1) }}
              >-</button>
              <input className="grp-btn-text" type="text"
                value={amount}
                readOnly/>
              <button 
                className="grp-btn-plus"
                onClick={(e) => { amountHandler(e, id, 1) }}
              >+</button>
            </div> :
            <button 
              onClick={(e) => { amountHandler(e, id, 1) }}
              className="add-menu-btn"
            >add</button>
          }
        </div>
      </div>
    )}}

通过这种方式,您可以在一个处理程序中处理所有事件,将整个订单状态保留在主要组件中……如果出现性能问题,只需使用PureComponent