首页 > 解决方案 > map() 中的三元运算符反应

问题描述

我在 React 中创建了一个使用州代码显示州假日的应用程序。现在我想知道当用户输入不存在的状态代码或更多字符时如何处理错误。这是我的尝试。

import React from "react";

const Holidays = props => {
if (props.dataLoaded === false) {
    return null;
  } else {
return (
  <div className="table-responsive">
    <table>
      <thead>
        <tr>
          <th>Holiday</th>
          <th>Date</th>
          <th>Type</th>
        </tr>
      </thead>
      <tbody>
        {props.country.map((country, index) =>
          country && index === undefined ? (
            <p>{props.error}</p>
          ) : (
            <React.Fragment key={index}>
              <tr>
                <td className="holiday-name">
                  <strong>{country.name}</strong>
                  <br />
                  <p>{country.description}</p>
                </td>
                <td className="holiday-date">
                  {country.date.datetime.day}.{country.date.datetime.month}.
                  {country.date.datetime.year}
                </td>
                <td className="holiday-type">
                  {country.type[0]} {country.type[1]}
                </td>
              </tr>
            </React.Fragment>
        )
          )}
          </tbody>
         </table>
       </div>
      );
    }
      };

 export default Holidays;

但是,当输入不存在的状态代码或更多字符时,使用此代码会引发错误“TypeError:无法读取未定义的属性'map'”。任何帮助都是可以接受的

标签: javascriptreactjsdictionaryoperator-keywordternary

解决方案


您的代码的问题是您props.country的数据在定义数据之前被映射,并且我们知道 map 方法.map()只能用于数组。在这里查看更多详情。因此,当您尝试使用map某些东西时,undefined它会抛出该错误。

最初的原因undefined是在大多数情况下,因为您正在从服务器或某些公共 API 从后端获取数据。在正在获取的数据的操作完成之前,您props.country将未定义或将其初始化为任何内容。

你应该做的是改变你当前的代码:

{props.country.map((country, index) =>
          country && index === undefined ? (
            <p>{props.error}</p>
          ) : (
            <React.Fragment key={index}>
              <tr>
                <td className="holiday-name">
                  <strong>{country.name}</strong>
                  <br />
                  <p>{country.description}</p>
                </td>
                <td className="holiday-date">
                  {country.date.datetime.day}.{country.date.datetime.month}.
                  {country.date.datetime.year}
                </td>
                <td className="holiday-type">
                  {country.type[0]} {country.type[1]}
                </td>
              </tr>
            </React.Fragment>
        )
)}

对于类似下面的内容,我们会检查您的内容props.country并确保它已加载 - 一旦加载,然后尝试使用map它来渲染内容。

{props.country ? props.country.map((country, index) =>
          country && index === undefined ? (
            <p>{props.error}</p>
          ) : (
            <React.Fragment key={index}>
              <tr>
                <td className="holiday-name">
                  <strong>{country.name}</strong>
                  <br />
                  <p>{country.description}</p>
                </td>
                <td className="holiday-date">
                  {country.date.datetime.day}.{country.date.datetime.month}.
                  {country.date.datetime.year}
                </td>
                <td className="holiday-type">
                  {country.type[0]} {country.type[1]}
                </td>
              </tr>
            </React.Fragment>
        )
): <div>Data Loading!</div>}

所以我们在这里所做的是添加另一个三元条件语句来检查if props.country是否true应用该map方法,否则您只需返回div内容为“数据加载!” 在加载数据之前。

为了澄清,我们将props.country ?在您的代码开头添加到左大括号{,并在最后一个: <div>Data Loading!</div>右括号之后)和右大括号之前}添加。

现在,这<div>Data Loading!</div>可能是您不必放置 div 或可以简单放置的文本的任何内容null,但在这些分秒内获取数据之前,您的输出将有空白空间。

尝试你想放在那里的东西,但最好的办法是放置一个像微调器这样的加载器或一个样式化的消息,以表明你的数据正在被获取。

编辑:您还可以将您的初始化props.country为一个数组,这样.map即使它为空,使用它也不会自动解析为错误。如果这是作为来自父组件状态的道具传递下来的,只需执行以下操作:

state = {
   country: []
}

不过,解决此问题的先前方法更好。但是您可能仍然应该习惯于使用它们最终将持有的数据来初始化您的状态属性。


推荐阅读