React JS输入字段在成功更新数组后没有更新

huangapple go评论69阅读模式
英文:

react js Input fields not updating after successful array update

问题

我有一组输入字段,由一个数组动态生成,本来应该默认填充为'?'。一旦用户在其中一个输入字段中输入一个字母,onchange 事件应该触发,并成功更新数组,重新填充输入字段的值。目前,如果我提供一个value={letter}作为属性,输入字段将如预期地填充,但填充输入字段的数组不会更新。如果我去掉value={letter},数组会如预期地更新,但输入字段当然不会填充。

const [letters, setLetters] = useState(workLetters);
function inputChangeHandler(event) {
  const incomingLetter = event.target.value;
  const nextLetters = [...letters];
  letters.forEach((letter, idx) => {
    if (letters_rec_of_truth[idx] === incomingLetter) {
      nextLetters[idx] = incomingLetter;
    }
  });
  console.log("next letters is now " + nextLetters);
  setLetters(nextLetters);
}
useEffect(() => {}, [letters]);
console.log("letters is now " + letters);

return (
  <div>
    {letters.map((letter, idx) => {
      return (
        <input
          type="text"
          key={idx}
          value={letter}
          onChange={inputChangeHandler}
        ></input>
      );
    })}
  </div>
);
英文:

I have a set of a input fields, dynamically generated by an array that are intended to be populated by default with a '?'. Once a user enters a letter into one of the inputs, the onchange event should fire and the array updates successfully, repopulating the inputs with the updated values. As of now, if I provide a value={letter} as an attribute, the inputs populate as expected, but the array that populates the inputs does not update. If I take value={letter} out, the array updates as expected, but the inputs of course, don't populate.

const [letters, setLetters] = useState(workLetters);
function inputChangeHandler(event) {
  const incomingLetter = event.target.value;
  const nextLetters = [...letters];
  letters.forEach((letter, idx) =&gt; {
    if (letters_rec_of_truth[idx] === incomingLetter) {
      nextLetters[idx] = incomingLetter;
    }
  });
  console.log(&quot;next letters is now &quot; + nextLetters);
  setLetters(nextLetters);
}
useEffect(() =&gt; {}, [letters]);
console.log(&quot;letters is now &quot; + letters);
//  console.log(evt);

return (
  &lt;div&gt;
    {letters.map((letter, idx) =&gt; {
      return (
        &lt;input
          type=&quot;text&quot;
          key={idx}
          value={letter}
          onChange={inputChangeHandler}
        &gt;&lt;/input&gt;
      );
    })}
  &lt;/div&gt;
);

答案1

得分: 0

为什么不使用'默认值'而使用'输入'标签的值?

英文:

Why instead of 'value' dont you use 'defaultValue' for the 'input' tag?

huangapple
  • 本文由 发表于 2023年1月9日 09:35:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75052485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定