重新更新数据时UseEffect挂钩无法正常工作?

时间:2020-09-05 07:00:38

标签: javascript reactjs react-native fetch

我有一个订单列表,我正在使用FlatList来呈现它们, 我应该有2个主要概念,即“加载更多,拉动刷新”

在我的情况下,用户可以编辑订单,然后拉动以刷新以获取新更新的数据,而在另一种情况下,可以加载更多“分页”。

SO 加载更多功能可以正常工作,并且可以从服务器获取新数据并与旧数据一起推入状态,

但是拉动刷新不起作用,尽管setState触发了获取数据的功能,但它并没有更新setState的数据,我可以在控制台中看到更新的数据,它只是呈现旧数据!

这是一个代码段。

const OpenedAppointments = () => {
  const [openedAppointment, setOpenedAppointment] = useState([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [lastPage, setLastPage] = useState(null);
  const [loading, setLoading] = useState(false);
  const [isFetch, setIsFetch] = useState(false);


 const loadMoreOrders = () => {
    if (currentPage <= lastPage - 1) {
      setLoading(true);
      setCurrentPage((prevPage) => prevPage + 1);
      console.log('loadMore??');
    }
  };


  const getOpenOrders = useCallback(() => {
    let AuthStr =
      'Bearer ';

    const headers = {
      'Content-Type': 'application/json',
      Authorization: AuthStr,
    };
    Api.post(
      `/open_orders?page=${currentPage}`,
      {},
      {
        headers,
      },
    )
      .then((res) => {
        let last_Page = res.data.open_orders.last_page;
        let allOpenedOrders = res.data.open_orders.data;
        console.log('allOpenedOrders', allOpenedOrders);
        console.log('last_Page', last_Page);
        console.log('currentPage', currentPage);
        setLastPage(last_Page);
        setOpenedAppointment((prevOpenedOrders) => [
          ...prevOpenedOrders,
          ...allOpenedOrders,
        ]);
        setLoading(false);
        setIsFetch(false);
      })
      .catch((err) => console.log('err', err));
  }, [currentPage]);
    
 // Delete Appointments
  const cancelAppointem = (appointmentID) => {
    let AuthStr =
      'Bearer...';

    const headers = {
      'Content-Type': 'application/json',
      Authorization: AuthStr,
    };
    Api.post(
      '/cancel/order',
      {
        id: appointmentID,
      },
      {
        headers,
      },
    )
      .then((res) => {
        setIsOpenedCancelModal((opened) => !opened);
        console.log(res.data);
        setOpenedAppointment((prev) =>
      prev.filter((item) => item.id !== appointmentID),
    ); // works very well
      })
      .catch((err) => console.log(err));
  };

  const _refresh = () => {
    setIsFetch(true);
    getOpenOrders();
  };

  useEffect(() => {
    getOpenOrders();
  }, [getOpenOrders]);

  const keyExtractor = (item, index) => String(index);



  return (
    <FlatList
      showsVerticalScrollIndicator={false}
      contentContainerStyle={styles.flatListCon}
      data={openedAppointment}
      ListEmptyComponent={renderEmpty}
      renderItem={renderItems}
      keyExtractor={keyExtractor}
      ListFooterComponent={_renderFooter}
      onEndReached={loadMoreOrders}
      onEndReachedThreshold={0.1}
      onRefresh={_refresh}
      refreshing={isFetch}
    />
  );
};

找出问题所在

在第一次渲染时,我从API获得了5个订单,如果我更新了第一个订单然后进行刷新,那么我又获得了相同的5个订单,但是订单号1已更新 因此,在getOpenOrders函数中,它将旧订单与新订单合并,因此我可以看到重复的订单的前5个订单“旧数据” 后5个顺序的“更新数据”。

但是我还有其他概念可以加载更多“分页”,因此我应该让合并数组在下一页“ 2”获得新的顺序,而在上一页“ 1”获得上一个的顺序!

那我该如何解决呢?

编辑数据结构响应

open_orders = [
   {id: 14, status: "Cash", cost: "25.00", service_id: 11, vendor_id: 3, …}
   {id: 15, status: "Cash", cost: "25.00", service_id: 11, vendor_id: 3, …}
    ...
]

2 个答案:

答案 0 :(得分:0)

您的效果应收听isFetch

  const _refresh = () => {
    setIsFetch(true);
  };

  useEffect(() => {
    getOpenOrders();
  }, [isFetch]);

答案 1 :(得分:0)

const [updatePage, setUpdatePage] = useState(1)
const [isUpdate, setIsUpdate] = useState(false)

// call `setUpdatePage` when you edit the data
/**
*  const edit = (record)=>{
*     ...
*     const updatePageIndex = openedAppointment.findIndex((item)=> item.id === record.id)
*     const updatePageNum = Math.ceil(updatePageIndex/openedAppointment.length)
*     setUpdatePage(updatePageNum)
*     setIsUpdate(true)
*  }
*  
**/
const getOpenOrders = useCallback(() => {
    const pageNum = isUpdate ? updatePage : currentPage
    let AuthStr =
      'Bearer ';

    const headers = {
      'Content-Type': 'application/json',
      Authorization: AuthStr,
    };
    Api.post(
      `/open_orders?page=${pageNum}`,
      {},
      {
        headers,
      },
    )
      .then((res) => {
        let last_Page = res.data.open_orders.last_page;
        let allOpenedOrders = res.data.open_orders.data;
        ...
        if(openedAppointment.length > 0) {
          const newOpenedOrders = openedAppointment.map((item)=>{
             const target = allOpenedOrders.find(ele=> ele.id === item.id) || []
             return {
              ...item,
              ...target,
             }
          })
          setOpenedAppointment(newOpenedOrders);
        } else {
          setOpenedAppointment(allOpenedOrders)
        }
        setIsUpdate(false)
        ...
      })
      .catch((err) => console.log('err', err));
  }, [currentPage]);