Use React's ref feature
This commit is contained in:
parent
fedeed15c5
commit
a4f5a7bdd7
2 changed files with 25 additions and 25 deletions
|
|
@ -34,8 +34,11 @@ class PostItem extends React.Component {
|
|||
ruleUrl = `${this.props.feedUrl}/${rule.id}/`;
|
||||
}
|
||||
|
||||
{
|
||||
/* TODO: figure out why this is called up to three times */
|
||||
}
|
||||
return (
|
||||
<li className="posts__item" data-id={post.id}>
|
||||
<li className="posts__item" ref={this.props.forwardedRef}>
|
||||
<h5
|
||||
className={titleClassName}
|
||||
title={post.title}
|
||||
|
|
|
|||
|
|
@ -11,29 +11,21 @@ import PostItem from './PostItem.js';
|
|||
|
||||
class PostList extends React.Component {
|
||||
handleIntersect = ::this.handleIntersect;
|
||||
lastPostRef = null;
|
||||
observer = null;
|
||||
lastPost = null;
|
||||
callCount = 0;
|
||||
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
this.lastPostRef = React.createRef();
|
||||
|
||||
const observerOptions = { root: null, rootMargin: '0px', threshold: 0 };
|
||||
this.observer = new IntersectionObserver(this.handleIntersect, observerOptions);
|
||||
}
|
||||
|
||||
componentDidUpdate() {
|
||||
const lastPost = [...this.props.postsByType]
|
||||
.reverse()
|
||||
.find(post => post.read === false);
|
||||
|
||||
if (lastPost && (!this.lastPost || lastPost.id != this.lastPost.id)) {
|
||||
const observeTarget = document.querySelector(
|
||||
`.posts__item[data-id="${lastPost.id}"]`
|
||||
);
|
||||
|
||||
this.lastPost = lastPost;
|
||||
this.observer.observe(observeTarget);
|
||||
if (this.lastPostRef.current) {
|
||||
this.observer.observe(this.lastPostRef.current);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -65,17 +57,22 @@ class PostList extends React.Component {
|
|||
|
||||
render() {
|
||||
const postItems = this.props.postsByType.map((item, index) => {
|
||||
return (
|
||||
<PostItem
|
||||
key={index}
|
||||
post={item}
|
||||
selected={this.props.selected}
|
||||
feedUrl={this.props.feedUrl}
|
||||
subredditUrl={this.props.subredditUrl}
|
||||
timelineUrl={this.props.timelineUrl}
|
||||
timezone={this.props.timezone}
|
||||
/>
|
||||
);
|
||||
const isLastItem = this.props.postsByType.length - 1 == index;
|
||||
const defaultProps = {
|
||||
key: index,
|
||||
post: item,
|
||||
selected: this.props.selected,
|
||||
feedUrl: this.props.feedUrl,
|
||||
subredditUrl: this.props.subredditUrl,
|
||||
timelineUrl: this.props.timelineUrl,
|
||||
timezone: this.props.timezone,
|
||||
};
|
||||
|
||||
if (isLastItem && !item.read) {
|
||||
return <PostItem {...defaultProps} forwardedRef={this.lastPostRef} />;
|
||||
} else {
|
||||
return <PostItem {...defaultProps} />;
|
||||
}
|
||||
});
|
||||
|
||||
if (isEqual(this.props.selected, {})) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue