为了账号安全,请及时绑定邮箱和手机立即绑定

无法在 React 中访问对象的属性

无法在 React 中访问对象的属性

拉风的咖菲猫 2022-06-16 15:30:42
我试图制作一个 onClick 事件并显示信息。当我执行console.log 来显示filteredSreen[0] 时,我得到了一个object( {id: "2", screen: "2", layer: "5", time: "13:15", dimension: "2D"})。当我想访问 id 或 screen 时,我做了console.log(filteredSreen[0].id) 或console.log(filteredSreen[0].screen)在 line6。他们都犯了同样的错误Cannot read property 'id' of undefined或 Cannot read property 'screen' of undefined我应该怎么做才能访问财产?===============================================screeninfo 是数组。[{id: "1", screen: "2", layer: "5", time: "13:15", dimension: "2D"},{id: "2", screen: "2", layer: "5", time: "13:15", dimension: "2D"},{id: "3", screen: "2", layer: "5", time: "13:15", dimension: "2D"}]它保存在 reduex 存储中,我将它传递给 BookInfo 组件。我发现 screeninfo 是使用 console.log 正确传递的。我还使用console.log检查了{id:“2”,屏幕:“2”,层:“5”,时间:“13:15”,维度:“2D”,}的结果。但我无法访问财产。我暂时这样做,我得到了正确的东西。// temporary wayconst filterScreen = () => {    let filteredSreen = screeninfo.filter((item) => item.id === screenId);    let result = filteredSreen[0];    let screen = "";    let layer = "";    for (let key in result) {      if (key === "screen") {        screen = result[key];      }      if ((key = "layer")) {        layer = result[key];      }    }    return screen,layer;  }const BookInfo = ({ movie, theater, screenId, date, screeninfo }) => {  const filterScreen = () => {    let filteredSreen = screeninfo.filter((item) => item.id === screenId);    let result = filteredSreen[0];    console.log(result); // {id: "2", screen: "2", layer: "5", time: "13:15", dimension: "2D",}  <=line5    console.log(result.id) // error  };  return (    <div className="bookInfo">      <div>{movie}</div>      <div>{theater}</div>      <div>{filterScreen()}</div>    </div>  );};
查看完整描述

2 回答

?
蝴蝶刀刀

TA贡献1801条经验 获得超8个赞

const BookInfo = ({ movie, theater, screenId, date, screeninfo }) => {

  const filterScreen = () => {

    let filteredSreen = screeninfo.filter((item) => item.id === screenId);

    let result = filteredSreen.length!==0 ? filteredSreen[0] :void 0 ;

    console.log(result); // {id: "2", screen: "2", layer: "5", time: "13:15", dimension: "2D",}  <=line5

    console.log(result.id) // error

  };


  return (

    <div className="bookInfo">

      <div>{movie}</div>

      <div>{theater}</div>

      <div>{filterScreen()}</div>

    </div>

  );

};


实际上,您的过滤条件并非每次都包含在 if 条件中


查看完整回答
反对 回复 2022-06-16
?
呼唤远方

TA贡献1856条经验 获得超11个赞

请添加条件


  const filterScreen = () => {

    let filteredSreen = screeninfo.filter((item) => item.id === screenId);

    let result = filteredSreen[0];

    if (result && result.id) { // condition 

       console.log(result);

       console.log(result.id);

    }

  };


查看完整回答
反对 回复 2022-06-16
  • 2 回答
  • 0 关注
  • 157 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信