反应useState,输入值不更新

时间:2020-04-07 12:29:25

标签: reactjs react-hooks use-state

我希望基于json生成输入,因此首先我将其设置为初始状态,然后在子componenet中我要修改它的字段,事情是该组件不会更新...它只渲染一次并且不知道如何使其在每次输入onChange更改其值时进行更新。知道如何在每次输入内容时更新输入值吗?

父母

 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>
  );
}

孩子

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>
);
}

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

3 个答案:

答案 0 :(得分:3)

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

let inputContent = [...inputValue];

这样做,将更改数组的引用并更新组件。

答案 1 :(得分:1)

只需更新您的代码,如下所示:

let inputContent = [ ...inputValue ];

答案 2 :(得分:1)

您正在突变状态对象。

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

记住,永不变异。