javascript - 改变状态会导致 props 改变

标签 javascript reactjs

我正在制作一个网络应用程序,人们可以点击鸡尾酒并更改配方以增加或减少每种成分的含量。为此,我首先从 API 端点加载饮料数据库,然后为数据库中的每种饮料创建一个子项,并将属性“drink”设置为定义饮料名称和配方的 JSON 对象。

每个 child 都有一个按钮来弹出一个模式,该模式有一个按钮组来调整每种成分的数量。我这样做的方法是将饮料配方作为属性传递给模式,然后将该配方从 Prop 复制到状态。

然后,当有人调整饮料配方时(他们可以为每种成分选择“低”、“常规”或“高”),我在模态上调用一个类函数,该函数传递配方列表中成分的索引,并乘以原始配方的常数。

在函数中,我设置了一个等于 props.recipe 的临时配方,然后将该因子乘以成分的原始数量。然后我通过调用 this.State 将已被因子修改的临时配方复制到状态

但是正在发生的事情是它似乎正在改变 props.recipe 以及 state.recipe。

为什么会发生这种情况?我不认为 Prop 是允许改变的。

其次,有没有更好的方法呢?我是新手,这是我的第一个网络应用程序。在最简单的形式中,我只是试图限制每种成分可以减少/增加的量,但仍然为最终用户提供更改它的选项。

Here is a screenshot with the console open所以你可以看到“之前”和“之后”如何改变,即使原始数量是3,它都是6。我点击“高”按钮,使成分的原始数量加倍,但如果我点击它它再次加倍,而不是停留在 6(这是 props 中存储的原始成分量的 2 倍)。

这是模式的代码:

import React from 'react';
import ReactDOM from 'react-dom';

import {Modal, ButtonGroup, Button, Table} from 'react-bootstrap';

export default class DrinkInfo extends React.Component {

  constructor(props){
    super(props);

    this.state = {
      recipe: props.drink.recipe,
    };

    console.log('Drink Info Initial Recipe is');
    console.log(this.props);
  }

  adjustAmount(ingredient, level){

    console.log('before change')

    var tempRecipe = this.props.drink.recipe;

    console.log(tempRecipe)

    tempRecipe[ingredient].amount = level * tempRecipe[ingredient].amount;
    //tempRecipe[ingredient].amount = level * this.props.drink.recipe[ingredient].amount;

    console.log('after change')
    console.log(tempRecipe)


    this.setState({ recipe: tempRecipe});
  }

  render(){

    const drinkName = this.props.drink.drink;
    //console.log(this.state.recipe)

    const recipeTableBody = this.state.recipe.map((di, value) => {
      //console.log(di.ingredient);
      return( 
        <tr key = {di.ingredient}>
          <td>{value}</td>
          <td>{di.ingredient}</td>
          <td>{di.amount}</td>
          <td>
            <ButtonGroup>
              <Button onClick={() => this.adjustAmount(value, 0.5)}> Low </Button>
              <Button onClick={() => this.adjustAmount(value, 1)}> Regular </Button>
              <Button onClick={() => this.adjustAmount(value, 2)}> High </Button>
            </ButtonGroup>
          </td>
        </tr>
      );
    });

    //{console.log('Creating Info Modal for: ' + this.props.drink.drink)}


    const recipeTable = (
      <Table striped bordered condensed hover>
        <thead>
          <tr>
            <th>#</th>
            <th>Ingredient</th>
            <th>Amount</th>
            <th>Adjust</th>
          </tr>
        </thead>
      <tbody>
        {recipeTableBody}
      </tbody>
      </Table>
    )

    return(
      <div>
        <Modal show={this.props.show} onHide={this.props.onHide} bsSize="large" aria-labelledby="contained-modal-title-sm">
          <Modal.Header closeButton>
            <Modal.Title id="contained-modal-title-sm"> {this.props.drink.drink} </Modal.Title>
          </Modal.Header>
          <Modal.Body>

            <h4> {this.props.drink.drink} Recipe </h4>

            {recipeTable}

          </Modal.Body>
          <Modal.Footer>
            <Button onClick={this.props.onHide}>Close</Button>
          </Modal.Footer>
        </Modal>

      </div>
    );
  }

}

最佳答案

正如有人提到的,尽量让 future 的问题更短、更简洁。这样可以更轻松地提供帮助。

也就是说,我想我在您的 adjustAmount() 函数中发现了您的问题。

看一下:

adjustAmount(ingredient, level){
  var tempRecipe = this.props.drink.recipe;
  tempRecipe[ingredient].amount = level * tempRecipe[ingredient].amount;
  this.setState({ recipe: tempRecipe});
}

您正在获取 this.props.drink.recipe 并将其设置为等于 tempRecipe。由于recipe是一个对象,这基本上在tempRecipe处创建了对该对象的引用。换句话说,tempRecipe === 配方

这意味着,当您更改 tempRecipe 时,您也在更改 recipe。虽然严格来说 React 不应该让你改变 props,但它没有任何东西可以卡住它们。 JavaScript 就是 JavaScript,所以它可以让你。

您应该做的是克隆 this.props.drink.recipe,然后使用克隆。

adjustAmount(ingredient, level){
  var tempRecipe = Object.assign({}, this.props.drink.recipe);
  tempRecipe[ingredient].amount = level * tempRecipe[ingredient].amount;
  this.setState({ recipe: tempRecipe});
}

这将assign()来自recipe的所有属性并将它们分配给一个新对象,从而有效地克隆它。

重要说明:Object.assign({}, someObj) 只会创建浅克隆。如果您的对象具有多个级别的深度(看起来确实如此),那么您应该获取或创建一个深度克隆对象,而不是 Object.assign()

只需获取其中一个,然后执行以下操作:

adjustAmount(ingredient, level){
  var tempRecipe = deepClone(this.props.drink.recipe);
  tempRecipe[ingredient].amount = level * tempRecipe[ingredient].amount;
  this.setState({ recipe: tempRecipe});
}

它们有很多,所以我不会在这里重新实现它们。拥有它们的几个库是 lodash、underscore,或者 NPM 中提供了一些独立的库。

关于javascript - 改变状态会导致 props 改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44641691/

相关文章:

javascript - Angular : get value of scope variable in a controller defined inside another controller which is inside directive

javascript - react 与 react DOM 混淆

javascript - 无法使用 D3 和 React 在 useEffect Hook 中进行画笔交互并设置状态

javascript - 引用错误: require is not defined @react

javascript - 为 ajax 弹出窗口发送文本值

javascript - 图片提交后如何取消预览?

javascript - 如何限制网站仅在 iframe 内加载?

lodash "set"方法的 javascript 实现

javascript - componentWillReceiveProps() 被触发但它没有获取 props

javascript - 如何将项目正确添加到 reactjs 中的状态(空数组)?