【问题标题】:update state in nested array react.js更新嵌套数组 react.js 中的状态
【发布时间】:2018-07-28 17:59:06
【问题描述】:

我正在尝试让两种方式绑定在反应中为嵌套数组工作。我让它为部门名称工作,这是一个简单的单一输入。问题是当我尝试在 handleInputChangeArray 中为我的团队数组设置状态时。应用程序中断,我收到一条错误消息,提示 this.state.team.map 不是函数。

  constructor(props) {
    super(props);
    this.state = {
      departmentName: '',
      team: [
        {
          name: '',
          title: '',
          salary: '',  
            }
          ]
        }
      ]

    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleInputChangeArray = this.handleInputChangeArray.bind(this);
  }

这是我的两个功能:

handleInputChangeArray(event) {
 const target = event.target;
 const value = target.type === 'checkbox' ? target.checked : target.value;
 const name = target.name;
 this.setState(({team}) => ({team: {
      ...team,
      [name]: value,
    }}))
  }

handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
  [name]: value
 });
}

此输入与我的 handleInputChange 完美配合

 <input  className="form-control" name=“departmentName” defaultvalue={this.state.departmentName} onChange={this.handleInputChange} type="text" />

这不起作用:

{this.state.team.map(( listValue, index ) => {
  return (
    <td key={index}>
      <input type="text" className="form-control" name="listValue.name" defaultValue={listValue.name}  onChange={this.handleInputChangeArray}  />
    </td>
    );
  })}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您还必须传入index 中应更新的team 数组中的哪个对象,以便您可以创建一个新对象,并将name 属性更改为value 以获取正确的元素.

    示例

    class App extends React.Component {
      handleInputChangeArray(event, index) {
        const { target } = event;
        const { name } = target;
        const value = target.type === "checkbox" ? target.checked : target.value;
    
        this.setState(prevState => {
          const team = [...prevState.team];
          team[index] = { ...team[index], [name]: value };
          return { team };
        });
      }
    
      render() {
        return (
          <tr>
            {this.state.team.map((listValue, index) => {
              return (
                <td key={index}>
                  <input
                    type="text"
                    className="form-control"
                    name="name"
                    defaultValue={listValue.name}
                    onChange={event => this.handleInputChangeArray(event, index)}
                  />
                </td>
              );
            })}
          </tr>
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 2017-04-30
      • 2018-11-02
      • 1970-01-01
      • 2019-01-28
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多