首页 > 解决方案 > 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.

标签: javascriptreactjs

解决方案


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()

推荐阅读