Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在REACT JS中保持先前更改的状态,因为当更新新项时,previous设置为default?_Javascript_Reactjs_Mapping_State_Shopping Cart - Fatal编程技术网

Javascript 如何在REACT JS中保持先前更改的状态,因为当更新新项时,previous设置为default?

Javascript 如何在REACT JS中保持先前更改的状态,因为当更新新项时,previous设置为default?,javascript,reactjs,mapping,state,shopping-cart,Javascript,Reactjs,Mapping,State,Shopping Cart,我在react中有一个购物车(不使用Redux),每个商品前面都有数量输入字段数量默认为1每种商品的总价格即为其信息(单价*1)。现在,如果用户更新数量值,则需要更新总价(单价*数量)。我的代码正在执行此操作,但问题是当我更新一个项目数量时,它会更新价格,很好,但当我更新另一个项目数量时,以前更新的价格会重置为默认值(返回单价) 我找了很多,但没有用。大多数人使用redux,但我不想使用它。因此,如果您看到解决方案,请帮助我,因为我希望保持所有更新的价格。 导出默认类购物车扩展组件 { 建造师

我在react中有一个购物车(不使用Redux),每个商品前面都有数量输入字段数量默认为1每种商品的总价格即为其信息(单价*1)。现在,如果用户更新数量值,则需要更新总价(单价*数量)。我的代码正在执行此操作,但问题是当我更新一个项目数量时,它会更新价格,很好,但当我更新另一个项目数量时,以前更新的价格会重置为默认值(返回单价)

我找了很多,但没有用。大多数人使用redux,但我不想使用它。因此,如果您看到解决方案,请帮助我,因为我希望保持所有更新的价格。

导出默认类购物车扩展组件
{
建造师(道具){
超级(道具);
此.state={
数据:[],
客户:'',
转发者:错,
购物车:[],
项目:[],
数量:'',
单击:'};
this.onChangeQty=this.onChangeQty.bind(this);
}
componentDidMount(){
检索到的常量=localStorage.getItem(“cartItem”);
const arr=JSON.parse(已检索);
轴心柱http://localhost/Auth/api/customers/show_cart.php'啊,,
{
标题:{'Accept':'application/json,text/plain,*/*',
“内容类型”:“应用程序/json”}
} )
。然后(响应=>{
这是我的国家({
cartItems:响应.数据.记录
});
})
.catch(错误=>{
如果(错误){
console.log(“错误”);}
});
}
变更数量(sid,e)
{
这是我的国家({
单击:sid,
数量:e.target.value})
}
render()
{
返回(
你的购物车
项目#
形象
身份证件
名称
单价
量
总价
{this.state.cartItems.map((项,i)=>
{i}
{item.SparePartID}
{item.Name}
{item.Price}
此.onChangeQty(item.SparePartID,e)}
/>
{
this.state.clicked==item.SparePartID?
(物料价格*本状态数量):物料价格
}
)}  
); }

}
您对每种商品都使用相同的状态,因此您对数量所做的每一次更改都会修改您的状态,从而修改所有商品的价格。没有必要为此使用redux。您可以做两件事:将项逻辑移动到子组件,这样,每个项都有自己的状态,或者,修改您的状态以处理对象数组,如
{name:'itemname',price:itemPrice等}
,这样您将只编辑特定项或使用qty属性改进cartItems:[]

编辑:

现在您可以尝试渲染我称之为ChartItem的n个子组件,它们将收到
{…item}
您可以看到的结果。通过
this.props.yourItemProp从组件内部使用

{this.state.cartItems.map( (item, i) => <ChartItem key={i} {...item} />}
{this.state.cartimes.map((item,i)=>}
现在,在每个ChartItem中,您都可以定义一个私有状态并使用它

  {this.state.cartItems.map( (item, i) => <ChartItem key={i} {...item}
onItemSomething={this.handleOnItemSomething}
{this.state.cartimes.map((item,i)=>}


因此,您可以调用this.props.onItemSomething与您的父组件通信

您需要做的是,当您获得购物车项目时,检查每个项目并为每个项目添加数量。并为所有产品的总数添加状态合计

constructor(props) {
      super(props);

      this.state = {
        data:[],
        customer: '',
        redirectToReferrer: false,
        cart: [],
        cartItems: [],
        totalPrice: 0
        clicked: ''      };
 this.onChangeQty = this.onChangeQty.bind(this);
}

componentDidMount() {

    const retrieved = localStorage.getItem("cartItem");
    const arr = JSON.parse(retrieved);
    axios.post('http://localhost/Auth/api/customers/show_cart.php', arr,
     {
    headers: {'Accept': 'application/json, text/plain, */*',
              'Content-Type': 'application/json'}
    } )
    .then(response => {
    let myItems = [];
    response.forEach(item => {
      myItems.push({id: item.id, name: item.name, qty: 1, price: item.price, total: item.price});
    })
    this.setState({
             cartItems :myItems
           });
      })
     .catch(error => {
     if (error) {
       console.log("Error");  }
       });

}
OnChange方法应找到所选产品并更新其数量和总价:

onChangeQty(sid,e)
{
  const items = this.state.cartItems;
  const item = items.find(item => item.id === sid);
  const index = items.indexOf(item);
  item.qty = e.target.value;
  item.total = item.qty * item.price;
  items[index] = index;

  let totalPrice = 0;
  items.forEach(item => {
      totalPrice += item.qty * item.price;
  });

  this.setState({
    cartItems: items,
    totalPrice
  });

}
在html中,您可以将总价显示为

{this.state.totalPrice}
如果你想要每个项目的总数,你可以简单地通过

this.state.cartItems.forEach(item => {
    console.log(item.total);
})

我认为您的问题在于您管理cartItems的方式。在OnChangeQuantity中,您应该迭代this.state.cartItems并找到具有所选sid的项目,您可以使用

onChangeQty (sid, {target:{value}}){

    let {cartItems } = this.state
    let ind = cartItems.findIndex( o => o.sid === sid) //get index and 
                                                       //update the 
                                                       // qty of 
                                                       // that element of the cartItems 
                                                       // array , 
     cartItems[ind].sid + = value

    this.setState({cartItems})
}

非常感谢您的回复。我想您在htm中的意思是我可以通过{this.state.totalPrice}来显示,尝试与您所说的相同,但它现在正在更新所有产品的价格,即使我更新了一个特定产品的数量。@YellowMinion是的,对不起,我在onchange方法中键入了错误,在setState中键入了total而不是totalPrice。我更新了代码,并再次检查您是否可以。然后让我知道它是否有效是的,我知道它是一个输入错误,所以我已经将“总计”更新为“总价”。但它是针对所有产品而不是特定产品更新TotalPrice。我认为它为所有产品设置了相同的TotalPrice状态。@YellowMinion现在检查一下。当您第一次从axios获得时,我已将total添加到每个产品中。然后在onChage事件中更新每个项目的total,最后它显示了您如何获得它的烦恼再一次。我做了同样的操作,它在这一行显示了错误const item=item.items.find(item=>item.id==sid);错误是说typeError:无法读取未定义的hanks的属性'items'以获得响应。我已更新了我的cartItems[]现在每个项目都有一个qty=1。现在请详细说明如何将我的逻辑移动到子组件?我是否应该在子组件中传递一个ID和qty道具,它将根据更新的数量计算总价?我将非常感谢您的帮助。@YellowMinion编辑的mu ansewer,希望这能帮助您