javascript - react : unable to map over state due to it being undefined/error

标签 javascript reactjs

我无法映射我的状态,传递给我的孙子 EmailDetails。在我尝试在 EmailDetails 的呈现函数中映射 urls 数组之前,我能够通过控制台记录它。

 import React, { Component } from "react";
    import IssueBox from "./issuebox.js";
    import "./App.css";

    class App extends Component {
      constructor(props) {
        super(props);

        this.state = {
          isLoaded: false,
          emails: [],
          counter: 0,
          title: "Test run",
          value: "",
          selectedEmailId: 0,
          currentSection: "inbox"
        };
      }

      componentDidMount() {
        fetch("blah")
          .then(res => res.json())
          .then(result => {
            const emails = result.data;
            console.log("resutl state: ", emails);
            let id = 0;
            for (const email of emails) {
              email.id = id++;
            }
            this.setState({
              isLoaded: true,
              emails: emails
            });
          });
      }

      handleClickReproducibleCounter(e) {
        let count = this.state.increment
          ? this.state.count + 1
          : this.state.count - 1;

        let increment = this.state.increment;

        if (count === 0) {
          increment = true;
        } else if (count >= 2) {
          increment = false;
        }

        this.setState({
          count,
          increment
        });
      }

      render() {
        return (
          <div className="App">
            <div>
              emails={this.state.emails}
              selectedEmailId={this.state.selectedEmailId}
              onEmailSelected={id => {
                this.openEmail(id);
              }}
              handleClickReproducibleCounter={this.handleClickReproducibleCounter}
            </div>
          </div>
        );
      }
    }

//数据如下所示:

[
  {
    groupID: "65da6a",
    urls: [
      {
        id: 85,
        searchedurl: "https://www.yahoo.com",
        errorurl: "https://www.yahoo.com/error505",
        count: 1,
        reproducible: false,
        reproducible_counter: 0
      },
      {
        id: 84,
        searchedurl: "https://www.gmail.com",
        errorurl: "https://www.gmail.com/error404",
        count: 1,
        reproducible: false,
        reproducible_counter: 0
      }
    ]
  },
  {
    groupID: "d4127e",
    urls: [
      {
        id: 3,
        searchedurl: "agwscc",
        errorurl: "xyqa",
        count: 1,
        reproducible: false,
        reproducible_counter: 0,
        resolved: null
      }
    ]
  }
];

//问题框.js

import React, { Component } from "react";
import "./App.css";
import EmailDetails from "./emailDetails";

class IssueBox extends Component {
  constructor(args) {
    super(args);
  }

  render() {

    const currentEmail = this.props.emails.find(
      x => x.id === this.props.selectedEmailId
    );
    console.log("emailDetail view: ", currentEmail); // email obj is present

    return (
      <div className="wrapper">
        <div className="inbox-container">
          <EmailList
            emails={this.props.emails}
            onEmailSelected={this.props.onEmailSelected}
            selectedEmailId={this.props.selectedEmailId}
          />

          <EmailDetails
            email={currentEmail} 
            onReproducibleCounter={this.props.handleClickReproducibleCounter}
            onValidateSumbit={this.props.handleClickValidateSumbission}
            handleTextInputChange={this.props.handleTextInputChange}
          />
        </div>
      </div>
    );
  }
}

export default IssueBox;

//电子邮件详细信息

import React, { Component } from "react";
import "./App.css";

class EmailDetails extends Component {
  constructor(args) {
    super(args);

    this.state = {
      counter: "",
      email: []
    };
  }

  componentDidUpdate(prevProps) {
    if (this.props.email !== prevProps.email) {
      this.setState({ email: this.props.email });
    }
  }

  render() {
    const currentEmail = this.state.email;
    console.log(currentEmail, this.state.email.urls); // able to console obj
    const test = this.state.email.urls.map(obj => {
      //error occurs here
      console.log(obj);
    });
    return (
      <div className="email-content">
        <div className="email-content__header">
          <h3 className="email-content__subject">Issue</h3>
          <div className="email-content__from">Group:</div>
        </div>
        <div className="email-content__message">
          <table role="table">
            <thead role="rowgroup">
              <tr role="row">
                <th role="columnheader">Searched URL</th>
                <th role="columnheader">Error URL</th>
                <th role="columnheader">NR</th>
                <th role="columnheader">Task</th>
              </tr>
            </thead>
            <tbody role="rowgroup" className="group-row" />
          </table>
        </div>

      </div>
    );
  }
}

export default EmailDetails;

以此为起点:codepen

最佳答案

我本来打算写一条评论,但它变得更长了,所以我决定改为提供一个答案。

理解您的代码有点困难,但我发现了一些问题和一些我不理解的地方。

首先,您没有在 App 中绑定(bind)您的 handleClickReproducibleCounter。因此,您不能将 this 用于回调函数。在您的构造函数中绑定(bind)它或改用箭头函数。

handleClickReproducibleCounter = (e) => {
...
}

其次,您在 EmailDetails 组件中使用此函数,例如:

<button onClick={this.props.onReproducibleCounter(obj.id)}>

为什么要使用 this.props?不需要 this,而且您已经从 Prop 中破坏了 onReproducibleCounter。此外,您没有在此处使用 onClick 处理程序的回调,而是立即调用带有参数的函数,这不是您真正想要的。

所以,它应该是这样的:

<button onClick={() => onReproducibleCounter(obj.id)}>

不过,使用箭头函数或绑定(bind) JSX props 中的函数并不是很好,因为它们会在每次渲染时重新创建。但是,在你的情况下,改变这个逻辑有点棘手。您正在将 Prop 传递给子组件并在那里映射一些东西。简单的方法是,在父组件中映射,然后将单个项目传递给子组件。

现在,我不明白的事情。您正在将一些 obj.id 传递给您的回调,但正在等待 e?而且您似乎没有在函数中的任何地方使用此参数。

我不明白的第二件事是在你的 map 中你使用第二个参数作为 onReproducibleCounter

email.urls.map((obj, onReproducibleCounter) => {

这里第二个参数是index

评论后更新

您正在使用异步作业在父级中获取此数据。当您尝试映射 this.state.email.urls 时,那时没有 this.state.email.urls 然后您会收到错误消息。

只要使用条件渲染或日志记录,随心所欲。

(this.state.email.urls || [] ).map(obj => {
      //error occurs here
    console.log(obj);
});

因此,如果没有 email.urls,那么我们的 map 将使用一个空数组,这对我们来说是可以的。 fetch完成后重新渲染组件,映射真实数据。

但是,不要将你的 Prop 编译成 child 的状态。在那里使用 email Prop 。如果您需要对其执行某些操作,请在您的子组件中执行。

这是一个非常简单和愚蠢的例子:

const Child = (props) => {
  const doSomething = () => {
    const newNumber = props.number * 20;
    props.handleNumber( newNumber );
  }
  return (
    <div>
    <button onClick={doSomething}>Click me, so do something in the Child and change this number.</button>
    </div>
  );
}

class App extends React.Component {
  state = {
    number: 10,
  }

  handleNumber = number => this.setState({number});

  render() {
    return <div>
    <p>Number is: {this.state.number}</p>
    <Child number={this.state.number} handleNumber={this.handleNumber} />
    </div>;
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

关于javascript - react : unable to map over state due to it being undefined/error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51864362/

相关文章:

javascript - 解码Javascript中的特殊字符

javascript - 按两个数字字段对 Javascript 数组进行排序

javascript - jQuery 对象和循环的问题

javascript - 根据唯一键/名称过滤状态数据数组并推送到新数组

reactjs - 如何在 React/Redux/Typescript 通知消息中卸载、取消渲染或删除组件

javascript - 点击事件冒泡问题

javascript - useRef 对象在 React/React-Native 中返回未定义

javascript - 拦截 react native webview 的每一个请求

javascript - 使用 redux hooks 时使用 redux Action 的最佳选择是什么?

javascript - Promise 解决方案不明确的问题