【问题标题】:Array of objects is undefined when page is rendered. Potential confusion when pages re-render呈现页面时未定义对象数组。页面重新呈现时的潜在混乱
【发布时间】:2021-03-29 09:45:33
【问题描述】:

我是 React 的新手,我目前正在努力解决这个我似乎无法找到解决办法的概念。我必须组件,父母和孩子。 Parent 组件通过 props 将数据传递给 Child 组件。我可以看到第一次渲染页面时正在传输数据,但我在控制台中注意到,页面的第二次和第三次渲染,数组返回为未定义。我不明白为什么数组是未定义的,是不是因为我没有在子组件中设置状态?

子组件代码:

export class NumOfDaysTable extends Component {
    static displayName = NumOfDaysTable.name;

    constructor(props) {
        super(props);
        this.state = {
            headers: [["Number", "Type", "Customer Name", "Customer", "Code", "Amount", "Date Submitted", "Notes", "Status"]],
            data: props.dataParentToChild
        };

    }
    render() {
        const { data } = this.state;
        console.log( data)
        const { headers } = this.state;
        
        return (
            <div>
                <h4 > {this.props.title} </h4>
                <Container>
                    <Table size="sm">
                        <thead>
                            {headers.map((headerData) => (
                                <tr>
                                    {headerData.map((headerRecord) => (
                                        <th>{headerRecord}</th>
                                        
                                    
                                    ))}
                                    </tr>
                                    ))}
                        </thead>

                        <tbody>
                            
                            {data.map((item) => ( 

                                
                                <tr>
                                     {item.map((record) => ( 
                                       <td>{record} </td> 
                                   ))}               
                                </tr>
                             ))} 

                        </tbody>

                    </Table>
                </Container>

            </div>
        );
    }
}


export default NumOfDaysTable; ```

【问题讨论】:

  • 您不想将道具重新分配到本地化状态,这可能是导致您的错误的原因。查看reactjs.org/docs/state-and-lifecycle.html
  • 我很困惑,现在当我开始的时候,也许这就是进步哈哈。根据文档,如果我的理解是正确的,我想使用 componentDidMount 来设置数据,然后在我的渲染中映射它。但是,当我添加它时,我的错误仍然是一样的。我仍然收到未定义的错误。
  • 嘿,我明白了,不用担心。不过要明确一点,不要尝试将道具分配给本地状态,无论是在constructor 还是componentDidMount。道具应该被子组件“接受”。也许数据最初是undefined,因此您可能需要在尝试访问该数据之前添加保护。

标签: javascript arrays reactjs react-native


【解决方案1】:

不要将你的道具重新分配给你的状态,当数据更新时你会失去反应性。

    constructor(props) {
        super(props);
        this.state = {
            headers: [["Number", "Type", "Customer Name", "Customer", "Code", "Amount", "Date Submitted", "Notes", "Status"]],
            // data: props.dataParentToChild --- REMOVE THIS LINE
        };

    }

然后调整你的渲染函数

    render() {
        const  data  = this.props.dataParentToChild;
        console.log( data)
        const { headers } = this.state;
// ...REST OF CODE

【讨论】:

    【解决方案2】:

    原因基本上是我们的 React 组件执行的顺序。仅用于初始渲染,没有数据,我们需要在项目中处理。

    您需要通过设置Only when data is passed to the Component render it. 我在子组件中使用{data &amp;&amp; (&lt;div&gt;...&lt;/div&gt;)} 的条件来呈现您的组件:

    这是可行的解决方案:

    父组件::传递道具

    import React from "react";
    import NumOfDaysTable from "./StackOverflow";
    
    const dataParentToChild = [
      {
        userId: 1,
        id: 1,
        title:
          "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
        body:
          "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto",
      },
      {
        userId: 1,
        id: 2,
        title: "qui est esse",
        body:
          "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla",
      },
      {
        userId: 1,
        id: 3,
        title: "ea molestias quasi exercitationem repellat qui ipsa sit aut",
        body:
          "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut",
      },
      {
        userId: 1,
        id: 4,
        title: "eum et est occaecati",
        body:
          "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit",
      },
      {
        userId: 1,
        id: 5,
        title: "nesciunt quas odio",
        body:
          "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque",
      },
    ];
    const Home = () => {
      return (
        <div>
          <h1>Home Page</h1>
          <NumOfDaysTable
            title="Reality Check"
            dataParentToChild={dataParentToChild}
          />
        </div>
      );
    };
    
    export default Home;
    

    子组件

    import React, { Component } from "react";
    export class NumOfDaysTable extends Component {
      //   static displayName = NumOfDaysTable.name;
    
      constructor(props) {
        super(props);
        this.state = {
          headers: [
            [
              "Number",
              "Type",
              "Customer Name",
              "Customer",
              "Code",
              "Amount",
              "Date Submitted",
              "Notes",
              "Status",
            ],
          ],
          data: props.dataParentToChild,
        };
      }
      render() {
        const { data } = this.state;
        const { headers } = this.state;
        console.log("Data Coming from the prop");
        console.log(data);
        return (
          <div>
            {data && (
              <>
                <h4> {this.props.title} </h4>
                <section>
                  <table size="sm">
                    <thead>
                      {headers.map((headerData) => (
                        <tr>
                          {headerData.map((headerRecord, index) => (
                            <th key={index}>{headerRecord}</th>
                          ))}
                        </tr>
                      ))}
                    </thead>
    
                    <tbody>
                      {data.map((item) => (
                        <tr key={item.id}>
                          <td>{item.title} </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </section>
              </>
            )}
          </div>
        );
      }
    }
    
    export default NumOfDaysTable;
    

    【讨论】:

      【解决方案3】:

      您必须在父组件中定义数据。

      看看codeSandBox

      // Parent component example
      
      import React from "react";
      import "./styles.css";
      
      import NumOfDaysTable from "./NumOfDaysTable.js";
      
      export default function App() {
        return (
          <NumOfDaysTable
            dataParentToChild={[
              [1,"Type 1","Customer 1","Name 1","Code 1","Amount 1","Date 1","Notes 1","Status 1"],
              [2,"Type 2","Customer 2","Name 2","Code 2","Amount 2","Date 2","Notes 2","Status 2"],
              [3,"Type 3","Customer 3","Name 3","Code 3","Amount 3","Date 3","Notes 3","Status 3"],
              [4,"Type 4","Customer 4","Name 4","Code 4","Amount 4","Date 4","Notes 4","Status 4"]
            ]}
          />
        );
      }
      

      并且不要忘记迭代时组件的唯一键!

      // NumOfDaysTable.js
      // code...
      
        render() {
          const { data } = this.state;
          console.log(data);
          const { headers } = this.state;
      
          return (
            <div>
              <h4> {this.props.title} </h4>
              <div>
                <table size="sm">
                  <thead>
                    {headers.map((headerData, id) => (
                      <tr key={"headerData" + id}>
                        {headerData.map((headerRecord, id) => (
                          <th key={"headerRecord" + id}>{headerRecord}</th>
                        ))}
                      </tr>
                    ))}
                  </thead>
                  <tbody>
                    {data.map((item, id) => (
                      <tr key={"item" + id}>
                        {item.map((record, id) => (
                          <td key={"record" + id}>{record}</td>
                        ))}
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          );
        }
      
      // code...
      

      【讨论】:

        猜你喜欢
        • 2018-07-26
        • 2021-12-01
        • 2021-01-20
        • 2012-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-12
        相关资源
        最近更新 更多