简体   繁体   中英

react-native: Component doesn't render in .map

Something doesn't seem right here. it doesn't render the Animated.View without using return , while I've seen this work in many examples. Any guesses why this behaviour?

在此处输入图片说明

I know there's been several answers already, but I believe they fail to address OP specific question of why it is doesn't work, especially given the new ES6 syntax.

tl;dr: ES6 arrow functions with block bodies do not implicity return.

From the docs:

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.

This is an example of "concise body", using the filter prototype:

let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let filteredArray = myArray.filter(item => item > 5);
console.log(filteredArray);
// => [6, 7, 8, 9, 10] 

In this expression, the lack of brackets { } mean that it will implicitly return the result of the expression.

The "block body" equivalent would be:

let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let filteredArray = myArray.filter(item => {
  return item > 5;
});
console.log(filteredArray);
// => [6, 7, 8, 9, 10] 

In your post, you are specifying your component inside the block body without returning it, and since the map prototype requires that you return the item inside the callback that will be used for the new map, the map is empty.

Directly return the Component in the anonymous function inside map

.map((d, i) => (<Component />))

or

.map((d, i) => <Component />)

See MDN docs :

The map() method creates a new array with the results of calling a provided function on every element in this array.

If the provided function doesn't return any data..you will have an array with undefined objects in it.

[1, 2, 3].map(function(){}) // [undefined, undefined, undefined]

As Bikas Vaibhav said in his comment and paraphrasing Mozilla Docs : map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results.

Therefore, if you do not return anything, you will have an array the same length as your ballArray only with undefined instead of a returned value. Try these two examples in your browser console.

With return:

> b = [1,4,9];
> d = b.map(function(a){
    var rt = a*2;
    return rt
});
<- [2, 8, 18]

Without return:

// Without a return:
> d = b.map(function(a){
    var rt = a*2;
});
<- [undefined, undefined, undefined]

Hope this helps!

With ES6 arrow functions you can do implicit returns like this:

this.state.ballArray.map((d, i) => (
  <Animated.View />
))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM