猿问

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

我试图制作一个 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 way

const 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>

  );

};


拉风的咖菲猫
浏览 158回答 2
2回答

蝴蝶刀刀

const BookInfo = ({ movie, theater, screenId, date, screeninfo }) => {&nbsp; const filterScreen = () => {&nbsp; &nbsp; let filteredSreen = screeninfo.filter((item) => item.id === screenId);&nbsp; &nbsp; let result = filteredSreen.length!==0 ? filteredSreen[0] :void 0 ;&nbsp; &nbsp; console.log(result); // {id: "2", screen: "2", layer: "5", time: "13:15", dimension: "2D",}&nbsp; <=line5&nbsp; &nbsp; console.log(result.id) // error&nbsp; };&nbsp; return (&nbsp; &nbsp; <div className="bookInfo">&nbsp; &nbsp; &nbsp; <div>{movie}</div>&nbsp; &nbsp; &nbsp; <div>{theater}</div>&nbsp; &nbsp; &nbsp; <div>{filterScreen()}</div>&nbsp; &nbsp; </div>&nbsp; );};实际上,您的过滤条件并非每次都包含在 if 条件中

呼唤远方

请添加条件&nbsp; const filterScreen = () => {&nbsp; &nbsp; let filteredSreen = screeninfo.filter((item) => item.id === screenId);&nbsp; &nbsp; let result = filteredSreen[0];&nbsp; &nbsp; if (result && result.id) { // condition&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;console.log(result);&nbsp; &nbsp; &nbsp; &nbsp;console.log(result.id);&nbsp; &nbsp; }&nbsp; };
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答