无法从渲染ReactJs返回const

时间:2019-03-13 13:17:49

标签: reactjs

我有这个组成部分。如果我执行console.log(insurance),它将显示一个保险对象,但是如果我尝试执行console.log(insurance.id),我将得到cannot read property 'id' of undefined

import React, { Component } from "react";

class EditInsurances extends Component {
  render() {
    const { insurances } = this.props;
    // get from url-route ID
    const insuranceId = this.props.match.params.id;

    const insurance = insurances.find(insurance => insurance.id == insuranceId);

   console.log(insurance.id);  <-error here( but if i do just 'insurance' it works
    return (
      <div>
        <p>Hello</p>
        <p>{insurance.tip}</p>  <-- also error here obv.
      </div>
    );
  }
}

export default EditInsurances

console.log(保险):

{id: 4, user_id: 1, tip: "Rovinieta", date_exp: "1977-02-13", date_notif: "1992-07-25", …}


created_at: "2019-03-11 09:49:23"
date_exp: "1977-02-13"
date_notif: "1992-07-25"
id: 4
note: "Et rem ea quia enim id incidunt."
tip: "Rovinieta"
updated_at: "2019-03-11 09:49:23"
user_id: 1
__proto__: Object

我该怎么做才能访问对象属性?

2 个答案:

答案 0 :(得分:2)

我猜想insurances数组来自异步数据源,当您第一次加载EditInsurances时,该数据仍在加载。

请牢记这一假设,当第一次渲染EditInsurances组件时,insurances道具将为空或为空。

如果您console.log(insurance),将获得一个空的控制台输出,然后是带有对象的另一个控制台输出。

如果您在第一个渲染上有console.log(insurance.id),它将出错,insurance.tip也会出现同样的情况,因为数据尚不可用。

如果存在保险,则应该仅渲染<EditInsurances insurances={...} />,或者通过prop-type验证并在假设数据正确之前检查数据来使EditInsurances组件更具弹性。

答案 1 :(得分:0)

另一种可能性

index.js

import React from "react";
import ReactDOM from "react-dom";
import EditInsurances from "./EditInsurances";
import "./styles.css";

function App() {
  const insurances = {
    id: "4",
    user_id: " 1",
    tip: "Rovinieta",
    date_exp: "1977-02-13",
    date_notif: "1992-07-25"
  };
return (
   <div className="App">
      <EditInsurances insurances={insurances} />
   </div>
   );
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

EditInsurances.js

class EditInsurances extends Component {
  render() {
     const { insurances } = this.props;
     // get from url-route ID
     const insuranceId = insurances.id;
     const insurance = Object.keys(insurances).map((item, indx) => {
         if (item[indx].id == insuranceId) {
            return item;
          }
     });

     return (
        <div>
        <p>Hello</p>
        <p>{insurances.tip}</p>
        </div>
     );
  }
}

 export default EditInsurances;

codesandbox exaple