【发布时间】: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