简体   繁体   English

具有动态数组长度的 React 钩子

[英]React hooks with dynamic array length

I have the following dummy example:我有以下虚拟示例:

function App({size}) {
  const [values, setValues] = React.useState(Array(size).fill(''));
  function onChange(index, event) {
    console.log('setting index: ', index)
    console.log('to value: ', event.target.value);
    values[index] = event.target.value;
    setValues(values);
  }

  console.log('values are');
  console.log(values);

  const inputs = Array(size).fill().map((_, index) => (
    <input
      key={`input-${index}`}
      value={values[index]}
      onChange={e => onChange(index, e)}
    />
  ));

  return (
    <React.Fragment>
      {inputs}
    </React.Fragment>
  )
}

ReactDOM.render(
  <App size={3} />,
  document.getElementById('container')
);

I expect to be able to pass size to App and dynamically get that many inputs.我希望能够将size传递给App并动态获取那么多输入。

When I run this and type in the inputs, I see当我运行它并输入输入时,我看到

values are
["", "", "", ""]
setting index: 3
to value: s
setting index: 1
to value: e
setting index: 0
to value: f

Looks like my component is not re-rendered.看起来我的组件没有重新渲染。 Why is that?这是为什么?

Your issue is most likely that you're trying to directly mutate state.您的问题很可能是您尝试直接突变 state。 In your onChange function, you should instead make sure not to try to mutate it.在你的onChange function 中,你应该确保不要试图改变它。

function onChange(index, event) {
  const newValues = values.map((value, i) => {
    return i === index ? event.target.value : value;
  });
  setValues(newValues);
}

As @Nick mentioned, the problem was that I was directly mutating the state itself.正如@Nick 提到的,问题是我直接改变了 state 本身。 I ended up using the following approach (instead of Nick's approach which does work):我最终使用了以下方法(而不是尼克的方法确实有效):

function onChange(index, event) {
  const newValues = [...values];
  newValues[index] = event.target.value;
  setValues(newValues);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM