【问题标题】:React useState - strange behaviour with useState and arraysReact useState - useState 和数组的奇怪行为
【发布时间】:2020-08-07 02:07:22
【问题描述】:

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

为什么会这样?

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;

【问题讨论】:

  • 您将setSimpleArray 的参数传递给Subcomponent 您的意思(根据传递给同一组件的参数名称判断)setTestSimpleArray。是这个问题吗?
  • 好皮卡,这是我最小示例的问题。交给我吧。

标签: reactjs react-hooks use-state


【解决方案1】:

问题

Subcomponent 被定义为采用setTestSimpleArray 属性

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

但是传递了一个 prop setSimpleArray 来代替

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

解决方案

正确传递道具

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

【讨论】:

  • 这是我最小示例中的错字,但对于我提供的示例来说肯定是正确的!谢谢。
猜你喜欢
  • 2021-04-14
  • 2021-08-01
  • 2021-12-30
  • 2020-04-13
  • 2020-11-02
  • 2020-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
相关资源
最近更新 更多