React useState,输入值不更新

React useState, value of input doesnt update

我希望根据 json 生成输入,所以首先我将它设置为初始状态,然后在 child componenet 中我想修改它的字段,问题是该组件没有更新.. . 它呈现一次,并且不知道如何在每次输入 onChange 更改它的值时更新它。知道如何在每次输入内容时更新输入值吗?

PARENT

 function App() {
      const [inputValue, setInputValue] = useState(chunkingRow);


  const handleChunkingChange = (e, index) => {
    let inputContent = inputValue;
    const reg = new RegExp(/^[0-9]+$/);

    if (e.target.value.match(reg)) {
      inputContent[index] = {
        ...inputContent[index],
        content: e.target.value,
      };

      setInputValue(inputContent);
      console.log(inputValue);
    } else console.log('not a number')
  };

  return (
    <div>
      <Wrapper>
        {Chunk(inputValue, handleChunkingChange)}
      </Wrapper>
    </div>
  );
}

CHILD

const Chunk = (inputValue, handleChunkingChange) => {

return(
  <div>
    {inputValue.map((el, index) => (
      <div key={index}>
        <p>{el.title}</p>
        {console.log(el.content)}
        <input
          type="text"
          onChange={(e, i) => handleChunkingChange(e, index)}
          value={el.content}
        />
      </div>
    ))}
  </div>
);
}

link 进行演示 https://codesandbox.io/s/stoic-mirzakhani-46exz?file=/src/App.js

不完全确定为什么会发生这种情况,但可能是因为您处理输入更改的方式。在我看来,该组件无法识别该数组已更改。我设法修复您的代码的方法是用以下代码替换 App 组件中的第 9 行:

let inputContent = [...inputValue];

通过这样做,数组的引用被更改并且组件被更新。

只需更新您的代码如下:

let inputContent = [ ...inputValue ];

您正在改变状态对象。

let inputContent = inputValue;

这就是不重新渲染状态的原因。将其更改为

 let inputContent = [...inputValue];

变异对象的一个​​例子。 React 比较以前的状态和当前状态,只有当它们不同时才渲染。

const source = { a: 1, b: 2 };
const target = source;
console.log(target);
console.log(target === source); =  true
target.b = 99;
console.log({target});
console.log({source}); //source == target due to mutation
console.log(source === target); = true

记住,永远不要变异。