如何从表单字段更新对象数组的状态?

时间:2018-03-14 23:30:03

标签: javascript reactjs

我创建了一个可用于创建新公司记录的组件。使用表单打开模态,并将值链接到状态值。在我的情况下,如果用户选择添加另一家公司,则可以创建多个公司记录。一个新的公司对象将被推送到公司状态,并将呈现新的空表单。

这是我根据此answer尝试的内容:

import { Component } from 'react';
import { Modal, Header, Form, Button, Icon, Tab, Segment } from 'semantic-ui-react';

export default class CompanyCreate extends Component {
  constructor(props) {
    super(props);

    this.state = {
      company: [
        {
          name: '',
          segment: ''
        }
      ]
    };

    this.initialState = this.state;

    this.handleChange = this.handleChange.bind(this);
    this.handleCompanyChange = this.handleCompanyChange.bind(this);
  }

  handleChange = (e, { name, value }) => this.setState({ [name]: value });

  handleCompanyChange = (e, { name, value }) => {
    const index = this.state.company.findIndex((x) => {
      return x[name] === value;
    });
    if (index === -1) {
      console.log('error');
    } else {
      this.setState({
        company: [
          ...this.state.company.slice(0, index),
          Object.assign({}, this.state.company[index], value),
          ...this.state.company.slice(index + 1)
        ]
      });
    }
  };

  render() {
    const { company } = this.state;

    return (
      <Segment>
            {company.map((e, index) => (
              <Form size="large" key={index}>
                <Form.Group>
                  <Form.Input
                    width={6}
                    onChange={this.handleCompanyChange}
                    label="Nome"
                    placeholder="Nome"
                    name="name"
                    value={e.name}
                    required
                  />
                  <Form.Input
                    width={6}
                    onChange={this.handleCompanyChange}
                    label="Segmento"
                    placeholder="Segmento"
                    name="segment"
                    value={e.segment}
                    required
                  />
                 </Form.Group>
              </Form>
            ))}
          </Segment>
    );
  }
}

我的问题是我无法正确设置公司状态。如何根据表单字段中的更改更新状态?

1 个答案:

答案 0 :(得分:0)

寻找答案,我找到了包裹:immutability-helper。基于这个answer,问题得到了简单而优雅的解决。

解决方案:

import update from 'immutability-helper';

//...

this.state = {
  company: [
    {
      name: '',
      segment: ''
    }
  ]
};

//...

handleCompanyChange = (e, { name, value, id }) => {
  let newState = update(this.state, {
    company: {
      [id]: {
        [name]: { $set: value }
      }
    }
  });
  this.setState(newState);
};

//...

render() {
const { company } = this.state;

return (
  <Segment>
        {company.map((e, index) => (
          <Form size="large" key={index}>
            <Form.Group>
              <Form.Input
                width={6}
                onChange={this.handleCompanyChange}
                label="Nome"
                placeholder="Nome"
                name="name"
                value={e.name}
                id={index}
                required
              />
              <Form.Input
                width={6}
                onChange={this.handleCompanyChange}
                label="Segmento"
                placeholder="Segmento"
                name="segment"
                value={e.segment}
                id={index}
                required
              />
             </Form.Group>
          </Form>
        ))}
      </Segment>
  );
}