【问题标题】:How do I show the value correctly in my form?如何在表单中正确显示值?
【发布时间】:2018-09-22 11:00:41
【问题描述】:

我正在尝试从我所在州的数据中生成一个:

const { id } = this.props.match.params;
const formGen = this.state.arr.map(arr => {
  if (id == arr.id) {
    const inner = this.state.arr.input.map(inputs => (
      <div>
        <h1>{arr.name}</h1>
        <label>{inputs.inputLabel}</label>
        <input value={inputs.inputValue} type={inputs.inputType} />
      </div>
    ));
  }
});

现在,我不知道如何让它显示在渲染选项卡中,因为我在变量中有一个变量:

<form />
        {formGen.inner}
      </div>

这是我正在尝试映射的状态

 arr: [
      {
        id: 1,
        name: 'firstForm',
        input: [
          {
            inputLabel: 'wowLabel',
            inputType: 'wowType',
            inputValue: 'wowValue'
          },
          {
            inputLabel: 'wowLabel2',
            inputType: 'wowType2',
            inputValue: 'wowValue2'
          }
        ]
      }

【问题讨论】:

  • 为什么不把 {formGen.inner} 放在表单中?

标签: arrays reactjs forms


【解决方案1】:

您可以返回它而不是将响应存储在变量中,否则返回 undefined 然后过滤掉响应。

const { id } = this.props.match.params;
const formGen = this.state.arr.map(arr => {
  if (id == arr.id) {
    return this.state.arr.input.map(inputs => (
      <div>
        <h1>{arr.name}</h1>
        <label>{inputs.inputLabel}</label>
        <input value={inputs.inputValue} type={inputs.inputType} />
      </div>
    ));
  }
  return;
}).filter(Boolean);

在这之后,你可以像这样渲染它

 <form />
    {formGen}
  </div>

【讨论】:

  • 非常感谢您的帮助!但似乎我还有另一个问题,我在评论中添加了我正在映射的状态,因为当我使用此代码时,它说“返回 this.state.arr.input.map 未定义”你碰巧知道为什么吗?
【解决方案2】:

const { id } = this.props.match.params;

// replace the first map with a find
const arr = this.state.arr.find(a => a.id == id);

// if arr is defined
if(arr){
    const inner = arr.input.map(inputs => (
      <div>
        <h1>{arr.name}</h1>
        <label>{inputs.inputLabel}</label>
        <input value={inputs.inputValue} type={inputs.inputType} />
      </div>
    ));

} else {
  // indicate to the user the that id was not found and what to do to fix the problem
}

&lt;form&gt;{inner}&lt;/form&gt;

【讨论】:

  • 我只有一个问题,你为什么用==而不是===,我注意到当我用===时它不起作用,即使它是相同的数字,你会发生吗知道为什么吗?
  • 我认为参数中的 id 是一个字符串,而你的状态 id 是一个数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多