React只更新状态的一个对象

时间:2017-11-03 13:45:41

标签: javascript reactjs

我有以下内容:

import React from 'react';
import Chart from './chart.jsx';

import Form from "./form.jsx";

import data from "./data.js";

class App extends React.Component {  
    constructor(props) {
        super(props)

        this.holdingArray = [];

        this.state = {
            newGraphData: "",
            startingIndex: "",
            endingIndex: "",
            form: {
                range1: {
                    month: "",
                    year: ""
                },
                range2: {
                    month: "",
                    year: ""
                }
            }
        }

        this.findIndex = this.findIndex.bind(this);
        this.generateNewData = this.generateNewData.bind(this);
        this.getValue = this.getValue.bind(this);
    }

    findIndex(month, year) {
        var indexVal = data.findIndex(i => i.yyyy == year && i.month == month);
        return indexVal;
    }

    generateNewData(index1, index2) {
        for (var i = index1; i < data.length; i++) {
            if(i <= index2){
                this.holdingArray.push({ year: parseInt(data[i].month), value: parseInt(data[i].tmax_C) });
            }
        }

        this.setState({
            newGraphData: this.holdingArray
        })
    }

    getValue(e) {
        let target = e.target,
            condition = target.name,
            value = target.value;

        switch (condition) {
          case 'range1-m':
            this.setState({
                form.range1.month: value
            })
            break;
          case 'range1-y':
            this.setState({
                form.range1.year: value
            })
            break;

          case 'range2-m':
            this.setState({
                form.range2.month: value
            })
            break;

          case 'range2-y':
            this.setState({
                form.range2.year: value
            })
            break;
        }

        console.log(this.state);
    }

    render() {

        return (
            <section>
                <Chart data={dataTest} />
                <Form getValue={this.getValue} />
            </section>
        )
    }
}

export default App;

“getValue”在以下内容中称为“onChange”:

import React from 'react';

class Form extends React.Component {  
  render() {
    return (
      <form className="form">
        <div className="form__range">
            <select onChange={this.props.getValue} name="range1-m">
              <option>1</option>
              <option>2</option>
              <option>3</option>
            </select>
            <select onChange={this.props.getValue} name="range1-y">
              <option>1970</option>
              <option>1971</option>
              <option>1972</option>
            </select>
            <select onChange={this.props.getValue} name="range2-m">
              <option>1</option>
              <option>2</option>
              <option>3</option>
            </select>
            <select onChange={this.props.getValue} name="range2-y">
              <option>1973</option>
              <option>1974</option>
              <option>1975</option>
            </select>
        </div>
        <div className="form__selection">

        </div>
        <div className="form__submission">
            <button onClick={this.props.submitForm}>submit</button>
        </div>
      </form>
    )
  }
}

export default Form;

我收到以下错误,怎么修复?是否有可能在当时更新状态对象的一部分?

enter image description here

4 个答案:

答案 0 :(得分:2)

您忘记在州内指定要更新的key

this.setState({
  form: {
    ...this.state.form,
    range1: {
       ...this.state.form.range1,
       month: value,
    }
  }
})

请注意setStateasynchronous,因此您无法立即访问它。

答案 1 :(得分:1)

您正在使用getValue方法改变您的州对象,即not advisable.

相反,你应该做以下事情。

getValue(e) {
        let target = e.target,
            condition = target.name,
            value = target.value;
           //This creates a new copy of the form object and 
           //does not change the existing object
           let newForm= JSON.parse(JSON.stringify(this.state.form));

        switch (condition) {
          case 'range1-m':
            newForm.range1.month: value
            break;
       ...
       }
        this.setState({
                form:newForm
            })
     ...
    }

顺便说一句,你应该尝试在你的州的形状中没有太多的嵌套级别,因为这会导致变化不可避免地发生变化。有关如何规范状态形状的提示,请managing the state shape in Redux提供建议。

修改:对于使用JSON.parse(JSON.stringify(obj))深层复制对象的任何疑虑,请查看https://stackoverflow.com/a/5344074/2345964

答案 2 :(得分:0)

在设置状态时,我不认为你可以比第一级对象/数组更深入。尝试查看切换功能,看看更像是:

case 'range1-m':
  const form = { ...this.state.form, range1: { ...this.state.fields.range1, month: value } }
  this.setState({ form })
  break

答案 3 :(得分:0)

您需要将当前状态与新值合并。

var newForm = Object.assign({}, this.state.form, {
    range1: Object.assign({}, this.state.form.range1, {
        month: value
    })
});

this.setState({
    form: newForm
});