Javascript 如何在React中的数组状态下保存用户输入的输入

Javascript 如何在React中的数组状态下保存用户输入的输入,javascript,arrays,reactjs,state,Javascript,Arrays,Reactjs,State,整个想法是以表单形式接受用户输入,并在JSON对象中显示他们的输入。在状态中,我有一个数组,其中有另一个数组 我的Form.js看起来像这样 state= { groups:[{ typeA:[{}], typeB:[{}] }], credentials: false }; change = e =>{ this.setState({[e.target.name]: e.target.value})

整个想法是以表单形式接受用户输入,并在JSON对象中显示他们的输入。在状态中,我有一个数组,其中有另一个数组

我的Form.js看起来像这样

state= {
    groups:[{
      typeA:[{}],
      typeB:[{}]
    }],
    credentials: false
    };

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

    handleSubmit(event) {
        event.preventDefault();
        this.setState({
          credentials: true 
        });
      }

我是React的初学者,无法在数组状态下存储字段值。

为了简单起见,我推荐以下解决方案, 您可以管理不同状态变量中的输入值,而不是在状态中使用嵌套数组,并在提交时将其更改为所需的输出

state = {
  field1: '',
  field2: '',
  field3: '',
  field4: '',
}
change = e => {
  this.setState({[e.target.name]: e.target.value})
};

handleSubmit(event) {
  event.preventDefault();
  const { field1, field2, field3, field4 } = this.state;
  // This is your output
  const output = [{typeA: [field1, field2], typeB: [field2, field3]}];
  this.setState({
    credentials: true 
  });
}
render(){
返回(
字段1:

字段2:
试试这个:

import React,{Component}来自“React”;
导出默认类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
小组:[
{
typeA:[{}],
类型B:[{}]
}
],
凭据:false
};
}
更改=(e,键)=>{
设{groups}=this.state;
设myVal=groups[0][e.target.name];
//或者,如果要在对象中添加值,如r[{value:'abcd'}]
myVal[0][key]=e.target.value;
组[0][e.target.name]=myVal;
console.log(“TCL:App->groups”,groups);
this.setState({groups});
};
render(){
返回(
此.change(e,“value2”)}
/>
this.change(e,“value”)}
/>

this.change(e,“value”)} /> ); } }
为每个输入指定一个自定义属性,例如
data group=“typeA”
。在on change函数中,获取该值并将值添加到正确的数组中

<input
  type="text"
  name="col2"
  placeholder="Type A"
  data-group="typeA" // add custom attribute typeA | typeB etc.
  onChange={e => this.change(e)}
/>
change = e => {

  // create a copy of  this.state.groups
  const copyGroups = JSON.parse(JSON.stringify(this.state.groups));

  // get data-group value
  const group = event.target.dataset.group;

  if (!copyGroups[0][group]) {
    copyGroups[0][group] = []; // add type if it doesn't exists
  }

  const groups = copyGroups[0][group];
  const index = this.findFieldIndex(groups, e.target.name);

  if (index < 0) {
    // if input doesn't exists add to the array
    copyGroups[0][group] = [...groups, { [e.target.name]: e.target.value }];
  } else {
    // else update the value
    copyGroups[0][group][index][e.target.name] = e.target.value;
  }

  this.setState({ groups: copyGroups });
};

函数formatState(json){
if(typeof json!=“string”){
json=json.stringify(json,未定义,2);
}
json=json.replace(//&/g,“&;”).replace(//g,”);
返回json.replace(/(“(\\u[a-zA-Z0-9]{4}\\\[^u]\\\\\\”)*”(\s*:)?\b(true | false | null)\b |-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)/g,(match)=>match);
}
常量凭据=({value})=>{
返回{formatState(value)};
};
类应用程序扩展了React.Component{
状态={
小组:[
{
类型A:[],
B类:[]
}
],
凭据:false
};
handleSubmit=事件=>{
event.preventDefault();
这是我的国家({
凭据:true//显示凭据组件
});
};
//获取数组typeA | typeB中的当前输入索引
findFieldIndex=(数组,名称)=>{
返回数组.findIndex(item=>item[name]!==未定义);
};
更改=e=>{
//创建此.state.groups的副本
const copyGroups=JSON.parse(JSON.stringify(this.state.groups));
//获取数据组值
const group=event.target.dataset.group;
如果(!copyGroups[0][group]){
复制组[0][group]=[];//添加新类型
}
常量组=复制组[0][group];
const index=this.findFieldIndex(组,如target.name);
如果(指数<0){
//如果输入不存在,请添加到数组
copyGroups[0][group]=[…groups,{[e.target.name]:e.target.value}];
}否则{
//更新值
copyGroups[0][group][index][e.target.name]=e.target.value;
}
this.setState({groups:copyGroups});
};
removeKey=(键)=>{
const temp={…this.state};
删除临时[键];
返回温度;
}
render(){
返回(
这个。更改(e)}
/>
这个。更改(e)}
/>
这个。更改(e)}
/>
这个。更改(e)}
/>
这个。更改(e)}
/>
提交
{this.state.credentials&&(
)}
);
}
}
ReactDOM.render(
,
document.getElementById('root'))
);

这给了我一个错误TypeError:无法获取未定义或空引用的属性“0”。我是否也需要更改输入标记内的“名称”仍然会给出相同的错误。我还尝试了myVal=groups[e.target.name][0](因此它采用name=“typeA”然后插入[0]索引)。你认为我应该使用映射来分配数组值吗?请再试一次!不!仍然不起作用:(它甚至不在返回中。给出了相同的错误“TypeError:无法获取未定义或空引用的属性“0”哇!它起作用了!对于后续列,只有一件事,如col2(typeA数组的第二个元素)以及第3列和第4列(类型B数组中的2个元素)。应该如何更改值?假设我在map函数中封装了,但是我应该如何在chnage函数中更改值索引omg!酷!谢谢!你能告诉我如何在不打印凭据的情况下打印JSON对象吗:true?我只是用它打印JSON对象使用delete好的,我明白了!谢谢我得到了它!谢谢你的帮助嗨,Junis,我有一个问题,它只是这个问题的一个扩展。我想知道是否有办法将输入值存储为一个数组(以及仅仅是值)。假设,如果我有一个列开始日期和结束日期:我想以数组的形式存储值。因此,我需要一个输出,如:typeA:[[col1value1,col1value2],[startdate,enddate]]。我知道这很复杂,但我认为输出应该是这样的。没关系,即使我没有将其实际存储在数组中
render(){
  return(
    <div class="classform">
      <form >
        <label>
          Field1:
          <br/>
          <input type="text"
            name="field1"
            placeholder="Type A"
            value={this.state.field1}
            onChange={this.change}
          />
        </label>
        <label>
          Field2:
          <br/>
          <input type="text"
            name="field2"
            placeholder="Type A"
            value={this.state.field2}
            onChange={this.change}
          />
        </label>
<input
  type="text"
  name="col2"
  placeholder="Type A"
  data-group="typeA" // add custom attribute typeA | typeB etc.
  onChange={e => this.change(e)}
/>
change = e => {

  // create a copy of  this.state.groups
  const copyGroups = JSON.parse(JSON.stringify(this.state.groups));

  // get data-group value
  const group = event.target.dataset.group;

  if (!copyGroups[0][group]) {
    copyGroups[0][group] = []; // add type if it doesn't exists
  }

  const groups = copyGroups[0][group];
  const index = this.findFieldIndex(groups, e.target.name);

  if (index < 0) {
    // if input doesn't exists add to the array
    copyGroups[0][group] = [...groups, { [e.target.name]: e.target.value }];
  } else {
    // else update the value
    copyGroups[0][group][index][e.target.name] = e.target.value;
  }

  this.setState({ groups: copyGroups });
};