您好,我必须将数组作为 props 传递给功能组件。
import React from "react";
import { render } from "react-dom";
const App = () => {
const FBS = ({ figures }) => {
console.log(typeof figures);
return figures.map((item, key) => <p key={key}>{item.description}</p>);
};
const figures = [
{
config: 112,
description: "description text 1"
},
{
config: 787,
description: "description text 2"
}
];
return (
<div>
{/* <FBS {...figures} /> */}
<FBS figures={figures} />
</div>
);
};
render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<body>
<div id='root' />
</body>
但是在子组件中转换为对象。 请查看渲染函数。当我将数组作为 {...figures} 传递时,我没有将它作为 FBS 组件中的数组获取,因此我无法在其上运行映射函数。而当我将它作为 figures={figures} 传递时,我得到一个数组。 我想将其作为{...数字}传递。
请帮忙
请查看我的代码以便更好地理解。 here
最佳答案
你需要有额外的对象,它有一对键和值,它们将作为你的 props
被解构到 React 组件。
const props = {
figures, // shorter way of writing figures: figures
// Any other objects you'd like to pass on as props
}
然后,您可以:
<FPS {...props} />
基本上你只能解构 React 组件中的对象,因为解构对象的键值对将成为组件的 props
。
为了更好的理解,
const arr = [{ a: 'a'}]
{...arr}
将给予:
{
0: {a: 'a'}
}
因为 0
是键,因为它是一个数组而不是对象,所以你真正做的是传递一个名称为 0
的 prop 而不是 figures
和 figures
是 undefined
,因此是错误。
关于javascript - 当我在 react 功能组件中传递数组时,它变成了一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55301315/