Skip to content

Commit

Permalink
make sure to check array bounds in VirtualizedSectionList (#23710)
Browse files Browse the repository at this point in the history
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: #23710

Differential Revision: D14298557

Pulled By: cpojer

fbshipit-source-id: fee3422ad5b053d91a097c5842f46e78a149c3d5
  • Loading branch information
vonovak authored and facebook-github-bot committed Mar 4, 2019
1 parent 7025cce commit 929908f
Showing 1 changed file with 12 additions and 9 deletions.
21 changes: 12 additions & 9 deletions Libraries/Lists/VirtualizedSectionList.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -234,26 +234,29 @@ 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 {
section,
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],
};
}
}
Expand Down

0 comments on commit 929908f

Please sign in to comment.