我正在尝试在 React 中创建数据网格,但在访问 props 中的数据时遇到了问题。每次我尝试访问数据或解构道具时,我的控制台都会显示“未定义”。
我只在 prop 是数组(对象)对象时才会收到此错误。当,只用一个字符串对象做同样的事情时,它似乎工作正常 - 所以我觉得我在这里错过了一些基本的东西。 罢工>
在以下摘录中,为了简洁起见,我删除了一些代码。在一个文件中,我有以下内容:
let inputRows = [
{ id: 0, title: "Task 1", complete: 20 },
{ id: 1, title: "Task 2", complete: 40 },
{ id: 2, title: "Task 3", complete: 60 }];
let inputCols = [
{ key: "id", name: "ID", editable: true },
{ key: "title", name: "Title", editable: true },
{ key: "complete", name: "Complete", editable: true }];
let matrixExample1 = {inputRows, inputCols};
const Tabs=(props) => {
return (
<div>
<MatrixParameter props={matrixExample1}>
<div>
);
在 MatrixParameter 文件中,我有以下内容:
const MatrixParameter = (props) => {
console.log(props);
let {
inputRows,
inputCols
} = props;
console.log(props);
console.log(props.inputRows);
console.log(inputRows);
return (
<*removed*>
)
Console.log 返回以下内容: reading the props successfully for the first two logs, but returning undefined for the next two logs. 我的代码的删除部分返回一个错误,说 inputRows 未定义。怎么回事?
(编辑:正如答案所建议的那样,我对字符串对象没有做同样的事情。错误是使用 <MatrixParameter props="matrixExample1"/>
错误地传递对象和/或失败通过使用 (props) 而不是 ({props}) 来弥补这一点。
答案 0 :(得分:2)
如评论和其他评论中所述,<MatrixParameter props={matrixExample1}>
使函数组件(名为 props
)的参数成为具有 .props
属性的对象。
但是,我认为您实际上并没有更改解构以使用它,而是使用 jsx 扩展属性
<MatrixParameter {...matrixExample1} />
相当于
<MatrixParameter inputRows={inputRows} inputCols={inputCols} />
答案 1 :(得分:1)
您已将它们作为键值为 props
的对象传递。所以它应该被破坏如下。
let {
inputRows,
inputCols
} = props.props;
您也可以使用这种销毁方法:
let {
props:{
inputRows,
inputCols
}
} = props;
答案 2 :(得分:0)
您将道具作为 MatrixParameter 的道具传递来修复您需要像使用它一样使用它的代码
props.props
//or like this
MatrixParameter = ({props})=>