【问题标题】:how do i update state in react for updating the value of an object inside an array using array.map function我如何更新状态以响应使用 array.map 函数更新数组内对象的值
【发布时间】:2020-01-19 08:12:13
【问题描述】:

函数 handleFeetAndInch 使用 index 更新状态,同时使用 array.map 并传递更新状态的函数,但映射的状态被引用给所有被调用的函数调用,因此其他映射索引不会获得更新的状态值,是否有围绕这种或其他方式转换值的做法,根据测量对象具有以下属性的情况: state = {measurements:[{name:'',value:'',algo:''}...]

handleFeetandInch = (key, nameValue, value) => {
  let realFeet = (value * 0.3937) / 12;
  let feet = Math.floor(realFeet);
  let inches = Math.round((realFeet - feet) * 12);
  let updatedValue = `${feet}'${inches}"`;
  const newMeasurement = [...this.state.measurements];
  newMeasurement[key] = {
    name: nameValue,
    value: updatedValue
  };
  this.setState({
    measurements: newMeasurement
  });
};

handleUnitChange = () => {
  if (this.state.isCm) {
    // reset State
  } else {
    this.state.measurements.map((measurement, key) =>
      measurement.algo === 1
        ? this.handleFeetandInch(key, measurement.name, measurement.value)
        : this.handleInches(key, measurement.name, measurement.value)
    );
    this.setState(prevState => ({
      isCm: !prevState.isCm
    }));
  }
};

【问题讨论】:

    标签: javascript reactjs data-structures state


    【解决方案1】:

    您没有正确使用地图功能。 array::map 返回一个新数组,原始数组的值映射到新值。

    更新handleFeeAndInch 只是映射回调,将新值返回到新数组中,然后那个数组设置状态。

    handleFeetandInch = (key, nameValue, value) => {
      let realFeet = (value * 0.3937) / 12;
      let feet = Math.floor(realFeet);
      let inches = Math.round((realFeet - feet) * 12);
      let updatedValue = `${feet}'${inches}"`;
    
      // return new measurement value
      return {
        name: nameValue,
        value: updatedValue
      };
    };
    
    handleUnitChange = () => {
      if (this.state.isCm) {
        // reset State
      } else {
        // get array of new measurements
        const newMeasurements = this.state.measurements.map((measurement, key) =>
          measurement.algo === 1
            ? this.handleFeetandInch(key, measurement.name, measurement.value)
            : this.handleInches(key, measurement.name, measurement.value)
        );
        this.setState(prevState => ({
          measurements: newMeasurements
        }));
        this.setState(prevState => ({
          isCm: !prevState.isCm
        }));
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-08
      • 2020-07-01
      • 1970-01-01
      • 2020-10-29
      • 2021-07-08
      • 2019-08-12
      • 2022-01-06
      • 1970-01-01
      相关资源
      最近更新 更多