简体   繁体   English

在 React Native 中使用外部 API 渲染 Flatlist 的正确方法

[英]Correct way to render Flatlist with external API in react Native

I have created a screen that has a flat list with a data source from an external API.我创建了一个屏幕,其中包含一个带有来自外部 API 的数据源的平面列表。 I am storing those data in a state, using redux and then retrieving the data to flatlist.我将这些数据存储在一个状态中,使用 redux 然后将数据检索到 flatlist。

I am for fetching the data from API I am using axios.我是为了从我使用 axios 的 API 中获取数据。 So, to supply the source of data to flatlist, I am fetching the data in the previous screen.因此,为了向 flatlist 提供数据源,我正在获取上一个屏幕中的数据。 For example - I have a button, by which on pressing that button it will navigate to a new screen which contains a flatlist.例如 - 我有一个按钮,按下该按钮它将导航到一个包含平面列表的新屏幕。 So, I am fetching the data by posting axios request by the onPress function of the button from the previous page.因此,我通过上一页按钮的 onPress 函数发布 axios 请求来获取数据。 And then storing that data to a state in the redux store, and then getting the data as a source to flat list.然后将该数据存储到 redux 存储中的状态,然后将数据作为源到平面列表。

I think this is not the right way to do this?我认为这不是正确的方法吗? How to fetch the data from external API on the same component and how to render that (because within fetching the data, the component will be rendered).如何从同一组件上的外部 API 获取数据以及如何呈现该数据(因为在获取数据时,将呈现该组件)。 How to do this effectively?如何有效地做到这一点?

As, if everything is correct if the user goes to some other screen and re-enters the screen what will happen?因为,如果一切都正确,如果用户转到其他屏幕并重新进入屏幕会发生什么? How to do this effectively and optimized?如何有效和优化地做到这一点?

I think I don't have any code to show.我想我没有任何代码可以显示。 If you guys need any code from above said, do let me know will update them.如果你们需要上面说的任何代码,请告诉我会更新它们。

You should probably try usingcomponentDidMount for calling your api.您可能应该尝试使用componentDidMount来调用您的 api。 componentDidMount is invoked only once, immediately after the initial rendering occur. componentDidMount 仅在初始渲染发生后立即调用一次。 You mentioned you are storing data in your redux store.您提到您将数据存储在您的 redux 存储中。

You should probably create events like:您可能应该创建如下事件:

const Actions = {
  LOAD_POSTS_REQUEST: 'LOAD_POSTS_REQUEST',
  LOAD_POSTS_FAILURE: 'LOAD_POSTS_FAILURE',
  LOAD_POSTS_SUCCESS: 'LOAD_POSTS_SUCCESS',
};

const postReducer = {
      posts: [],
      isLoaded: false
};

Now, on LOAD_POSTS_SUCCESS you can set your data which you need in the flatlist with that also set a isLoaded state in the redux store.现在,在LOAD_POSTS_SUCCESS您可以在LOAD_POSTS_SUCCESS中设置您需要的数据,并在 redux 存储中设置isLoaded状态。 Now next time, when user re-enters the screen you can use the state.isLoaded check to call the api.现在下一次,当用户重新进入屏幕时,您可以使用state.isLoaded检查来调用 api。

I am sure that what I am mentioning here is a way simple implementation.我确信我在这里提到的是一种简单的实现方式。 Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM