make sure to check array bounds in VirtualizedSectionList (#23710)

Summary:
SectionList accesses items outside of the array bounds.

This was discovered when using mobx, which warns you: `[mobx.array] Attempt to read an array index (${index}) that is out of bounds`. This is because `section.data[itemIndex + 1]` goes beyond array length.

This PR adds an array length check and simplifies the code a bit to avoid repetitive `this.props.`
Pull Request resolved: https://github.com/facebook/react-native/pull/23710

Differential Revision: D14298557

Pulled By: cpojer

fbshipit-source-id: fee3422ad5b053d91a097c5842f46e78a149c3d5
This commit is contained in:
Vojtech Novak 2019-03-03 20:27:42 -08:00 коммит произвёл Facebook Github Bot
Родитель 7025cce3f4
Коммит 929908f287
1 изменённых файлов: 12 добавлений и 9 удалений

Просмотреть файл

@ -221,9 +221,9 @@ class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
trailingSection?: ?SectionT,
} {
let itemIndex = index;
const defaultKeyExtractor = this.props.keyExtractor;
for (let ii = 0; ii < this.props.sections.length; ii++) {
const section = this.props.sections[ii];
const {sections} = this.props;
for (let ii = 0; ii < sections.length; ii++) {
const section = sections[ii];
const key = section.key || String(ii);
itemIndex -= 1; // The section adds an item for the header
if (itemIndex >= section.data.length + 1) {
@ -234,7 +234,7 @@ class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
key: key + ':header',
index: null,
header: true,
trailingSection: this.props.sections[ii + 1],
trailingSection: sections[ii + 1],
};
} else if (itemIndex === section.data.length) {
return {
@ -242,18 +242,21 @@ class VirtualizedSectionList<SectionT: SectionBase> extends React.PureComponent<
key: key + ':footer',
index: null,
header: false,
trailingSection: this.props.sections[ii + 1],
trailingSection: sections[ii + 1],
};
} else {
const keyExtractor = section.keyExtractor || defaultKeyExtractor;
const keyExtractor = section.keyExtractor || this.props.keyExtractor;
return {
section,
key: key + ':' + keyExtractor(section.data[itemIndex], itemIndex),
index: itemIndex,
leadingItem: section.data[itemIndex - 1],
leadingSection: this.props.sections[ii - 1],
trailingItem: section.data[itemIndex + 1],
trailingSection: this.props.sections[ii + 1],
leadingSection: sections[ii - 1],
trailingItem:
section.data.length > itemIndex + 1
? section.data[itemIndex + 1]
: undefined,
trailingSection: sections[ii + 1],
};
}
}