【问题标题】:Better ways to deal with React properties toString or similar method处理 React 属性 toString 或类似方法的更好方法
【发布时间】:2021-09-29 08:38:17
【问题描述】:

我自己作为初学者正在修复一些 React 组件,在这个特定的部分中,有一个信息列显示了一个企业的联系链接和信息。

在元素呈现的 return 语句之后,我试图做的是隐藏列,如果每个值的长度从 API 传递。因此我尝试使用 .length 方法。

主要问题是当我尝试在诸如 business.email.toString 之类的东西上使用 toString 方法时,属性给了我 TypeErrors。 准确地说,错误是:

TypeError:无法读取未定义的属性“toString”

我选择了另一种在此之前有效的方法,在所有 4 个属性中应用类似于以下内容的方法:

  business.email = new String(business.email).valueOf();

但是,我意识到以这种方式使用对象可能会影响性能。当前解决方案不使用该 String 对象方法,但如果这些属性之一为空,则可能会导致错误。我意识到这可能与 React State 及其钩子有关,或者我没有以正确的方式使用道具,因为我仍在学习使用它们的道路上。

感谢任何和所有的意见,以更好地做到这一点!

这是当前的代码部分。

//Imports


interface Props {
  top?: boolean;
}

const BusinessDescription: FC<Props> = (props) => {
  const locBusiness: BusinessModel = useSelector(
    (state: any) => state.locationsReducer.business
  );
  const [business, setBusiness] = useState<any>([]);

  useEffect(() => {
    if (!locBusiness || !locBusiness.id) return;
    BusinessHomepageAPI.getHomepage(locBusiness.id).then((response) => {
      setBusiness(response.data);
    });
  }, [locBusiness]);

  function addhttp(url: string) {
    ...
    return url;
  }

  business.web_page = addhttp('' + business.web_page);
  business.phone_number = '' + business.phone_number;
  business.whatsapp_number = ''+ business.whatsapp_number;
  business.email = ''+ business.email;

  return (
    <Col className={props.top ? style._contactUs1 : style._contactUs2}>
      {business.phone_number.length > 4 ||
      business.whatsapp_number.length > 4 ||
      business.email.length > 4 ||
      business.web_page.length > 10 ? (
        <span className={`${style.__container} ${style.__title}`}>
          <Translate id="BusinessInfo.ContactUs" />
        </span>
      ) : null}
    ...
    //rest of render and visual elements

【问题讨论】:

标签: reactjs react-hooks react-props use-effect


【解决方案1】:

TypeError: 无法读取未定义的属性“toString”

当您尝试在当前未定义的内容上调用方法或属性时会引发此错误。

根据使用的位置,您可以使用if 语句、三元语句或可选链接来解决此问题。

if 语句

// Create variable to store value (initialise with preferred default).
let email = undefined;

// Check if property is 'truthy', which in this case should mean it has a value.
if (business.email) {

    // Use 'toString()' on a value you know not to be 'undefined'.
    email = business.email.toString();
}

三元语句

// Same as an if statement above but more compact.
// May be better or worse depending on coding principles / standards
const email = business.email ?      // The condition (check property is turthy)
    business.email.toString() :     // If the condition is true (use 'toString()')
    undefined;                      // If the condition is false (use default)

// Can be written on a single line
const anotherEmail = business.email ? business.email.toString() : undefined;

可选链接

// Shorter / neater than the other two options.
// This does not give you control to change the default value if 
// 'business.email' is not defined.
const email = business.email?.toString();

// This can essentially be written as a ternary statement
const email = busness.email !== null && business.email !== undefined ? 
    business.email.toString() : 
    undefined;

// To change the default value you can assigned when 'business.email' 
// is undefined you can group with a null-coalescing operator.
const email = business.email?.toString() ?? 'default@email.com';

【讨论】:

  • 哇,感谢您的出色回答!我将研究哪种实现最适合,尽管我认为三元语句在这种情况下最适合。
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2010-09-25
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 2011-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多