【发布时间】:2021-02-27 17:57:31
【问题描述】:
我正在尝试在 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})。
【问题讨论】:
-
您的
props对象有一个名为props的键。您要么需要解构props.props,要么将解构移到左侧let {props : { inputRows, inputCols } } = props
标签: javascript reactjs typescript react-props destructuring