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

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

react js Input fields not updating after successful array update

问题

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

  1. const [letters, setLetters] = useState(workLetters);
  2. function inputChangeHandler(event) {
  3. const incomingLetter = event.target.value;
  4. const nextLetters = [...letters];
  5. letters.forEach((letter, idx) => {
  6. if (letters_rec_of_truth[idx] === incomingLetter) {
  7. nextLetters[idx] = incomingLetter;
  8. }
  9. });
  10. console.log("next letters is now " + nextLetters);
  11. setLetters(nextLetters);
  12. }
  13. useEffect(() => {}, [letters]);
  14. console.log("letters is now " + letters);
  15. return (
  16. <div>
  17. {letters.map((letter, idx) => {
  18. return (
  19. <input
  20. type="text"
  21. key={idx}
  22. value={letter}
  23. onChange={inputChangeHandler}
  24. ></input>
  25. );
  26. })}
  27. </div>
  28. );
英文:

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.

  1. const [letters, setLetters] = useState(workLetters);
  2. function inputChangeHandler(event) {
  3. const incomingLetter = event.target.value;
  4. const nextLetters = [...letters];
  5. letters.forEach((letter, idx) =&gt; {
  6. if (letters_rec_of_truth[idx] === incomingLetter) {
  7. nextLetters[idx] = incomingLetter;
  8. }
  9. });
  10. console.log(&quot;next letters is now &quot; + nextLetters);
  11. setLetters(nextLetters);
  12. }
  13. useEffect(() =&gt; {}, [letters]);
  14. console.log(&quot;letters is now &quot; + letters);
  15. // console.log(evt);
  16. return (
  17. &lt;div&gt;
  18. {letters.map((letter, idx) =&gt; {
  19. return (
  20. &lt;input
  21. type=&quot;text&quot;
  22. key={idx}
  23. value={letter}
  24. onChange={inputChangeHandler}
  25. &gt;&lt;/input&gt;
  26. );
  27. })}
  28. &lt;/div&gt;
  29. );

答案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:

确定