反应useState-useState和数组的奇怪行为

时间:2020-08-07 02:07:22

标签: reactjs react-hooks use-state

使用下面的示例组件,将'setter'从useState传递到子级中,对于字符串而言,但对于数组而言,效果很好。它说设置器(仅用于数组)不是“函数”。在父级中使用二传手效果很好。通过在父级中调用方法来解决该问题也可以,但是我不明白为什么需要这样做。

为什么会这样?

import React, { useState } from 'react';

function App() {

  const [testString, setTestString] = useState('initial string value');
  const [testSimpleArray, setTestSimpleArray] = useState(['one initial', 'two initial']);

  const handleArrayChange = (arg) => {
    setTestSimpleArray(arg);
  }


  return (
    <>
      <Subcomponent
        testString={testString}
        setTestString={setTestString}
        testSimpleArray={testSimpleArray}
        setSimpleArray={setTestSimpleArray}
        altArrayChanger={handleArrayChange}

      ></Subcomponent>

      <button onClick={() => setTestSimpleArray(['new from parent', 'new two from parent'])}>Set array in parent (works)</button>
    </>
  );
}

子组件

function Subcomponent({testString, setTestString, testSimpleArray, setTestSimpleArray, altArrayChanger}) {
  
  
    return (
      <>
        <div>
          <h2>String</h2>
          {testString} <br />
          <button onClick={() => setTestString('boo')}>setting string from subcomponent is ok</button>
        
          <h2>Array</h2>
          {JSON.stringify(testSimpleArray)} <br />
          <button onClick={() => setTestSimpleArray(['new from subcomponent', 'new two from subcomponent'])}>Set array in subcomponent fails</button>

          <button onClick={() => altArrayChanger(['new alt from subcomponent', 'new alt two from subcomponent'])}>Workaround (call parent event to do the update there)</button>

        </div>
      </>
    );
  }
  
export default App;

1 个答案:

答案 0 :(得分:0)

问题

Subcomponent被定义为使用setTestSimpleArray道具

Subcomponent({
  testString,
  setTestString,
  testSimpleArray,
  setTestSimpleArray, // <--
  altArrayChanger
})

但是却传递了一个道具setSimpleArray

<Subcomponent
  testString={testString}
  setTestString={setTestString}
  testSimpleArray={testSimpleArray}
  setSimpleArray={setTestSimpleArray} // <--
  altArrayChanger={handleArrayChange}
/>

解决方案

正确传递道具

<Subcomponent
  testString={testString}
  setTestString={setTestString}
  testSimpleArray={testSimpleArray}
  setTestSimpleArray={setTestSimpleArray} // <--
  altArrayChanger={handleArrayChange}
/>

Edit react-usestate-strange-behaviour-with-usestate-and-arrays