【问题标题】:Destructuring a props object returns undefined解构 props 对象返回 undefined
【发布时间】: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 是未定义的。怎么回事?

(编辑:正如答案所建议的那样,我没有对字符串对象做同样的事情。错误是使用&lt;MatrixParameter props="matrixExample1"/&gt; 错误地传递了对象和/或未能补偿为此,使用 (props) 而不是 ({props})。

【问题讨论】:

  • 您的props 对象有一个名为props 的键。您要么需要解构props.props,要么将解构移到左侧let {props : { inputRows, inputCols } } = props

标签: javascript reactjs typescript react-props destructuring


【解决方案1】:

如 cmets 和其他内容中所述,&lt;MatrixParameter props={matrixExample1}&gt; 导致功能组件(名为 props)的参数成为具有 .props 属性的对象。

但是,我认为您的实际意图是使用 jsx 传播属性,而不是更改解构以使用它

<MatrixParameter {...matrixExample1} />

相当于

<MatrixParameter inputRows={inputRows} inputCols={inputCols} />

【讨论】:

    【解决方案2】:

    您已将它们作为键值为props 的对象传递。所以它应该被破坏如下。

    let {
            inputRows,
            inputCols
        } = props.props;
    

    你也可以使用这种销毁方式:

       let {
            props:{
            inputRows,
            inputCols
            }
        } = props;
    

    【讨论】:

    • "所以它应该被破坏如下。" - 不。相反,它的传递方式应该是固定的。
    【解决方案3】:

    您将 props 作为 MatrixParameter 的 prop 传递来修复您需要使用它的代码

    props.props 
     //or like this 
    MatrixParameter = ({props})=>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-30
      • 2021-05-13
      • 1970-01-01
      • 2020-11-02
      • 2017-09-09
      • 2020-09-16
      • 1970-01-01
      • 2021-07-31
      相关资源
      最近更新 更多