如何处理可能未定义的数据上的调用函数? [英] How to handle calling functions on data that may be undefined?

查看:31
本文介绍了如何处理可能未定义的数据上的调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要使用 React,并且经常发现当我编写一个依赖于组件状态的函数时,我必须在执行任何操作之前执行检查以查看该状态是否已定义.

I primarily work with React and often find that when I write a function that relies on a component's state, I have to perform a check to see if the piece of state is defined before performing any actions.

例如:我有一个函数,它使用 .map() 循环遍历从数据库中获取的对象数组,并为数组中的每个对象生成 jsx.这个函数在我的组件的 render() 函数中调用.第一次调用 render() 时,初始数组为空.这会导致错误,因为当然,数组的第一个索引未定义.

For example: I have a function that uses .map() to loop over an array of objects fetched from a database and generates jsx for each object in the array. This function is called in the render() function of my component. The first time render() is called, the initial array is empty. This results in an error because, of course, the first index of the array is undefined.

我一直在通过进行条件检查以查看数组的值是否未定义来规避这一点.每次编写 if 语句的过程都感觉有点笨拙,我想知道是否有更好的方法来执行此检查或完全避免它.

I have been circumventing this by making a conditional check to see if the value of the array is undefined or not. This process of writing an if statement each time feels a little clumsy and I was wondering if there is a better way to perform this check or a way to avoid it entirely.

推荐答案

使用map前检查数组:

Check the array before using map:

arr && arr.map()

或,

arr && arr.length && arr.map() // if you want to map only if not empty array

或,

我们甚至可以这样使用(如 devserkan 所评论):

We can even use like this (as commented by devserkan):

(arr || []).map()

<小时>

根据您的评论:


As per your comment:

我希望有一个像 C# 一样安全的导航操作符 (arr?.map())

I wish there was a safe navigation operator like with C# (arr?.map())

是的,很明显.这在 JavaScript 中称为 可选链,目前仍在提案中.如果它被接受,那么你可以这样使用:

Yes, obviously. This is called optional chaining in JavaScript which is still in proposal. If it is accepted, then you may use like this:

arr?.map()

您可以在 staging 1 中看到它,您可以使用 babel 预设 stage1

You can see it in staging 1 for which you may use babel preset stage1

但显然,除了检查数组长度外,您的要求将无法满足:

But obviously, except the checking array length, your requirement will not be fulfilled:

这会导致错误,因为当然,数组的第一个索引未定义.

This results in an error because, of course, the first index of the array is undefined.

所以,我建议你使用:

arr && arr.length && arr.map()

这篇关于如何处理可能未定义的数据上的调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆