简体   繁体   English

如何在本机反应中动态更新 FlatList?

[英]How to update the FlatList dynamically in react native?

Initially loading data from API to FlatList using setState and it loaded perfectly.最初使用 setState 将数据从 API 加载到 FlatList 并完美加载。 But I have to perform some actions like create, update & delete of FlatList row.但我必须执行一些操作,例如创建、更新和删除 FlatList 行。 When I try to add new data to the FlatList, the data is not rendered in FlatList with an updated one, but In API it's updated.当我尝试将新数据添加到 FlatList 时,数据不会在 FlatList 中呈现更新的数据,但在 API 中它已更新。

How to re-render the flatlist after updating to the API and load the new data to FLatList?更新到 API 后如何重新渲染 flatlist 并将新数据加载到 FLatList?

Here is my code:这是我的代码:

  constructor(props) {
    super(props);
    this.state = {
        faqs: [],

    }

    this.loadFaq();

 };

To load the data to FlatList from the API:要将数据从 API 加载到 FlatList:

 loadFaq = async () => {
    let resp = await this.props.getFaqGroup();
    if (resp.faqs) {
        
        console.log(resp.faqs)
        this.setState({
            faqs: resp.faqs,
            // refresh: !this.state.refresh
        })

    }

   };

To add new data to API:要将新数据添加到 API:

 createFaqGroup = async (name) => {
    let resp = await this.props.createFaqGroup(name);
    // console.log("resp", resp)
    // this.setState({
    //     refresh: !this.state.refresh
    // })
    // this.forceUpdate();

    this.closePanel();

}

FlatList code:平面列表代码:

    {this.state.faqs && <FlatList
                    extraData={this.state.faqs}
                    horizontal={false}
                    data={this.state.faqs}
                    contentContainerStyle={{ paddingBottom: 75 }}

                    renderItem={({ item: faqs }) => {

                        return <Card gotoQuestionList={this.gotoQuestionList} key={faqs._id} faqs={faqs} openPanel={(selectedFaq) => this.openPanel({ name: selectedFaq.name, id: selectedFaq._id })} deletePanel={(selectedFaq) => this.deletePanel({ name: selectedFaq.name, id: selectedFaq._id, isPublished: selectedFaq.isPublished })}></Card>
                    }

                    }
                    keyExtractor={(item) => item._id}
                />}

this.props.createFaqGroup function code: this.props.createFaqGroup function 代码:

export const createFaqGroup = (name) => {
  const options = {
    method: 'POST',
    data: { "name": name },
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${store.getState().auth.info.token}`
    }
};
return async (dispatch) => {
    console.log('url::', options)
    try {
        let url = `${config.baseUrl}${config.faqUrl}`;
        let resp = await axios(url, options);
       
        console.log(resp.data)
        return resp && resp.data ? resp.data : null;
    } catch (error) {
        alert(error)
        if (error.response && error.response.status === 401) {
            dispatch({
                type: type.ERROR,
                data: error.response.data
            });
        } else {
            dispatch({
                type: type.CREATE_FAQ_GROUP_ERROR,
                error: error.message
            });
        }
    }
 };

}

Any help much appreciated pls...任何帮助非常感谢请...

I think you should load data again, after you add them, so you can modify your function createFaqGroup like this:我认为您应该在添加数据后再次加载数据,这样您就可以像这样修改您的 function createFaqGroup

createFaqGroup = async (name) => {
  let resp = await this.props.createFaqGroup(name);
  this.loadFaq();

  this.closePanel();
}

Try this:尝试这个:

createFaqGroup = async (name) => {
  let resp = await this.props.createFaqGroup(name);
  this.setState({faqs: [...this.state.faqs, name]})

  this.closePanel();
}

Flatlist will update automatically when you set your state ie by using this.setState() function, it means whenever any changes made to your state variable it will rerender your flatlist.当您设置 state 即使用 this.setState() function 时,Flatlist 将自动更新,这意味着只要对您的 state 变量进行任何更改,它就会重新显示您的 flatlist。 if you still face the same problem remove your this.state.faqs && part , this looks unnecessary because there is no need to check if you are passing the empty array to faltlist or not, flatlist allows you to pas empty array as well, it will not give you any error.如果您仍然遇到同样的问题,请删除您的this.state.faqs && 部分,这看起来没有必要,因为无需检查您是否将空数组传递给 faltlist,flatlist 也允许您传递空数组,它不会给你任何错误。

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

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