javascript - How to handle calling functions on data that may be undefined?
问题描述
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.
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.
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.
解决方案
Check the array before using map:
arr && arr.map()
OR,
arr && arr.length && arr.map() // if you want to map only if not empty array
OR,
We can even use like this (as commented by devserkan):
(arr || []).map()
As per your comment:
I wish there was a safe navigation operator like with C# (arr?.map())
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()
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.
So, I suggest you to use:
arr && arr.length && arr.map()
推荐阅读
- automation - 如何等待浏览器直到数据被填充到下拉框中而不在 puppeteer 中使用 delay()?
- mobx - mobx自动运行没有触发
- r - 如何将 rma() 标准化应用于唯一的 CEL 文件?
- v8 - 如何转换本地
到一个字符串? - python - 根据 python 中 stats.linregress 的输出计算置信区间
- google-apps-script - 如何创建模拟 RANK 公式的自定义函数?
- sql - 如何选择 distinct 但在决赛桌中包含所有其他变量?
- php - 用 php 操作一个字符
- ruby-on-rails - 如何使用 PATCH 表单在网站上添加 POST 表单?
- regex - 用匹配的正则表达式的特定组中的值替换散列的键