如何防止React-Native挂钩与Redux中的重复数据

cyvaqqii  于 2022-11-24  发布在  React
关注(0)|答案(2)|浏览(200)

我是redux的新手,我使用react原生钩子和redux。我的问题是,在打开articleScreen.js页面后,单击后退按钮并再次打开articleScreen.js页面,数据再次呈现,因此当在articleScreen.js页面上单击时,有相同的数据并重复显示相同的数据。
网站Map=〉

const ArticleScreen = () => {
  const dispatch = useDispatch();
  const data = useSelector((state) => state.articleReducer.data);
  const isLoading = useSelector((state) => state.articleReducer.isLoading);
  const [loadingMore, setLoadingMore] = useState(false);
  const [page, setPage] = useState(1);
  const currentPage = useSelector((state) => state.articleReducer.currentPage);
  const totalPage = useSelector((state) => state.articleReducer.totalPage);
  const nextPage = useSelector((state) => state.articleReducer.nextPage);

  useEffect(() => {
    dispatch(fetchingArticle({ page: 1 }));
  }, [])

  const _renderItem = ({ item, index }) => {
    return (
      <TouchableOpacity
        key={`${item.id} ${page}`}
        style={{ marginBottom: 16 }}
      >
        <View style={{ flexDirection: 'row' }}>
          <View style={{ flex: 1 }}>
            <Text>{item.title}</Text>
          </View>
        </View>
      </TouchableOpacity>
    );
  };

  const handleLoadMoreData = () => {
    if (!isLoading) {
      setLoadingMore(true)
      if (nextPage <= totalPage) {
        dispatch(fetchingArticle(nextPage));
      } else {
        setLoadingMore(false)
      }
    }
  }

  return (
    <>
      <View>
        <FlatList
          data={data}
          renderItem={_renderItem}
          keyExtractor={item => `${item.id}`}
          onEndReached={handleLoadMoreData}
          onEndReachedThreshold={0.01}
          ListFooterComponent={
            loadingMore && (
              <View
                style={{
                  marginVertical: 30,
                }}>
                <ActivityIndicator
                  size="large"
                  color={Colors.onSurface}
                />
              </View>
            )
          }
        />
      </View>
    </>
  );
};

export default ArticleScreen;

=〉商店. js

const middleware = applyMiddleware(thunk);

// Root Reducer
const rootReducer = combineReducers({
  articleReducer: ArticleReducer,
});

// Redux Store
const store = createStore(
  rootReducer,
  middleware
)

export default store;

=〉文章操作. js

export const fetchArticleRequest = () => ({
  type: 'FETCH_ARTICLE_REQUEST',
});

export const fetchArticleSuccess = (data) => ({
  type: 'FETCH_ARTICLE_SUCCESS',
  payload: data.data
});

export const fetchArticleFailure = (error) => ({
  type: 'FETCH_ARTICLE_FAILURE',
  payload: error
});

export const fetchingArticle = (page) => {
  return async dispatch => {
    dispatch(fetchArticleRequest());
    return apiRequest.get(URL.articles + '?page=' + page).then((response) => {
      dispatch(fetchArticleSuccess(response.data));
    })
      .catch((error) => {
        dispatch(fetchArticleFailure("Request Data Error"))
      })
  }
}

=〉文章还原器. js

const initialState = {
  data: [],
  error: '',
  isLoading: false,
  refreshing: false,
  currentPage: 1,
  totalPage: 1,
  nextPage: 0,
  totalData: 0
};

const ArticleReducer = (state = initialState, action) => {
  switch (action.type) {
    case 'FETCH_ARTICLE_REQUEST':
      return {
        ...state,
        isLoading: true,
        refreshing: true,
      };
    case 'FETCH_ARTICLE_SUCCESS':
      return {
        ...state,
        data: state.data.concat(action.payload.data),
        isLoading: false,
        refreshing: false,
        currentPage: action.payload.current_page,
        totalPage: action.payload.last_page,
        nextPage: action.payload.current_page + 1,

      };
    case 'FETCH_ARTICLE_FAILURE':
      return {
        ...state,
        error: action.error,
        isLoading: false,
        refreshing: false,
      };

    default:
      return state;
  }
};

export { ArticleReducer };
1l5u6lss

1l5u6lss1#

我不知道Redux,但也许你只需要加载你的数据一次,而不是每次你调用你的页面,除非你清除,你有之前提取他们。
我会让其他人谁知道我更redux(我不能评论,所以不要把这个答案算作答案!)

ufj5ltwl

ufj5ltwl2#

问题出在你的减速器上。你把以前的数据和新的数据合并为

data: state.data.concat(action.payload.data)

如果“获取文章成功”:将上一行更改为

data: action.payload.data

喜欢

case 'FETCH_ARTICLE_SUCCESS':
      return {
        ...state,
        data: action.payload.data,
        isLoading: false,
        refreshing: false,
        currentPage: action.payload.current_page,
        totalPage: action.payload.last_page,
        nextPage: action.payload.current_page + 1,

      };

相关问题