即使将FlatList中渲染的组件声明为PureComponent并且其prop引用未更改,它们也会重新渲染

时间:2019-07-10 11:08:23

标签: reactjs react-native redux react-redux immutability

我正在使用Redux开发一个React本机应用程序,其中我在页面中获取帖子,每个页面包含5个帖子并将它们呈现在FlatList中。呈现“主页”屏幕后,我将获取帖子的第一页,并使用商店中最初为空的帖子数组对其进行填充。当用户向下滚动时,我去获取帖子的下一页,并用posts数组对其进行隐藏。问题在于,在获取帖子的下一页并将其与现有帖子数组进行隐蔽处理时,我注意到上一页面中已呈现在FlatList中的现有帖子被重新呈现。我通过登录componentDidUpdate生命周期方法来检测到这一点。

这是我在主屏幕中呈现帖子FlatList的方式:

renderPostsList = () => {
        const { posts, onFetchPosts, postsComments } = this.props;

        return(
            <FlatList 
              style = { styles.postsList }
              keyExtractor = { item => item.id.toString() }
              onEndReachedThreshold = { 0.5 }
              onEndReached = { ({distanceFromEnd}) => { onFetchPosts() } }
              data = { posts }
              renderItem = { ({ item }) => { 
                  return(
                      <Post 
                        userName = { item.user.username }
                        time = { item.created_at }
                        content = { item.onlyText }
                        commentsCount = { item.commentCount }
                        likesCount = { item.likeCount }
                        dislikesCount = { item.dislikeCount }
                        sharesCount = { item.shareCount }
                        comments = { postsComments.get( item.id ) }
                        fetchCommentsHandler = { this.getFetchCommentsHandlerForPost( item ) }
                      />
                  );  
                }
              }  
            />
        );
};

这是getFetchCommentsHandlerForPost方法:

getFetchCommentsHandlerForPost = post => {
      return () => {
        if ( post.commentCount > 0 ) {
          this.props.onFetchComments( post.id );
        }
      };
};

这里是onFetchPosts动作的创建者:

export const fetchPosts = () => ( dispatch, getState ) => {
    const { nextPage } = getState().posts;

    if ( !nextPage ) {
        return;    
    }

    dispatch( startLoading() );

    const user = getState().auth.user.user;

    const userId = user
        ? user.id
        : null;

    axios( '/posts', {
        method: 'GET',
        params: {
            userId,
            page: nextPage
        }
    } )
    .then( res => {
        const posts = res.data.data.map( item => {
            if ( !item.user ) {
                item.user = { username: 'No Name' };
            }

            return item;
        } );

        dispatch( appendPosts( posts ) );

        const { current_page, last_page } = res.data.meta;
        const nextPage = current_page === last_page? null : current_page + 1;
        dispatch( updateNextPage( nextPage ) );

        dispatch( stopLoading() );            
    } )
    .catch( err => {
        dispatch( stopLoading() );
        dispatch( setError( i18n.t( 'errors.fetch_posts_failed' ) ) )
    } );
};

这是职位减少者:

import { APPEND_POSTS,
    START_LOADING,
    STOP_LOADING,
    POSTS_SET_ERROR,
    POSTS_CLEAR_ERROR,
    UPDATE_NEXT_PAGE } from '../actions/ActionTypes';

const initialState = {
    posts: [],
    nextPage: 1,
    isLoading: false,
    error: null
};

const postsReducer = ( state = initialState, action ) => {
    switch( action.type ) {
        case APPEND_POSTS:
            return {
                ...state,
                posts: state.posts.concat( action.payload.posts )
            };
        case UPDATE_NEXT_PAGE:
            return {
                ...state,
                nextPage: action.payload.nextPage
            };
        case START_LOADING:
            return {
                ...state,
                isLoading: true
            };
        case STOP_LOADING:
            return {
                ...state,
                isLoading: false
            };
        case POSTS_SET_ERROR:
            return {
                ...state,
                error: action.payload.error
            };
        case POSTS_CLEAR_ERROR:
            return {
                ...state,
                error: null
            };
        default:
            return state;
    }
};

export default postsReducer;

由于FlatList和我的Post组件是PureComponent,我希望现有的帖子在上一个和新的帖子数组中具有相同的引用,因此不应重新呈现它们。

2 个答案:

答案 0 :(得分:1)

您似乎需要向key中添加Post

<Post 
    key = {item.id}                        
    userName = { item.user.username }
    time = { item.created_at }
    content = { item.onlyText }
    commentsCount = { item.commentCount }
    likesCount = { item.likeCount }
    dislikesCount = { item.dislikeCount }
    sharesCount = { item.shareCount }
    comments = { postsComments.get( item.id ) }
    fetchCommentsHandler = { this.getFetchCommentsHandlerForPost( item ) }
 />

现在React可以分辨出哪些是新的,哪些是先前的。

答案 1 :(得分:0)

如果您使用FlatList从REST API呈现动态数据或分页数据,则不应将FlatList用作PureComponent。 PureComponent不应该具有状态,这就是为什么当props更改时整个Component都将被重新渲染。您可以在此处使用Post作为PureComponent,但不能使用整个FlatList。试试看,不要将FlatList用作PureComponent。将Post用作PureComponent,将组件Key用作key = {postitem.id}

当Component用作纯组件时,它不保持任何状态,在这里,FlatList是PureComponent,因此一旦数据更改,它就会为该{{1}调用呈现函数},并且完全重新启用。