使用下面的示例组件,将'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;
答案 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}
/>