Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

javascript - 如何从数组中删除元素并在FlatList上没有该元素的情况下更新状态?(How to remove an element from array and update state without that element on the FlatList?)

I am trying to remove the data from a FlatList that it renders the sales from a JSON file data.json The problem is that when I remove the sale with a certain id and I go back to home page, it shows all the items again.(我正在尝试从FlatList删除数据,该数据从JSON文件data.json呈现销售信息。问题是,当我删除具有特定ID的销售信息并返回首页时,它将再次显示所有项目。)

So how can I remove the items from the source and the items will be removed for the whole life of the application until the user closes and reopens again?(因此,如何从源中删除项目,并且在用户关闭并再次重新打开之前,这些项目将在应用程序的整个生命周期中被删除?) Any help would be very much appreciated.(任何帮助将不胜感激。) import data from './data.json'; { "sales": [ { "id": 1, "amount": 100 }, { "id": 2, "amount": 200 }, ] } state = { data: data.sales } onPressRemove(id) { this.setState( prevState => { let data = prevState.data.slice(); let newId = 0; for (var i=0; i < data.length; i++){ if (data[i].id === id){ newId = i; } } data.splice(newId, 1) return { data }; }); }   ask by Sachihiro Takamori translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem right here is that where you go to another part of your app this component will UNMOUNT and when you go back to this component he will mount and use the state from the import (data.json).(此处的问题是,当您转到应用程序的另一部分时,该组件将取消安装 ,当您返回该组件时,它将安装并使用导入状态(data.json)。)

For this kind of problem, many people choose to go with redux .(对于这种问题,许多人选择使用redux 。) Another way would be to keep the state on the parent and give it as a prop to this component, so even when that will unmount and mount again it will still have the prop unchanged (because parent never unmounts).(另一种方法是将状态保留在父级上,并将其作为对此组件的支持,因此即使将其卸载并再次安装,它仍将保持prop不变 (因为父级不会卸载)。) If you have more questions in implementation, feel free to comment/share your code if you stuck implementing my answer.(如果您在执行中还有其他问题,如果您坚持执行我的答案,请随时评论/共享您的代码。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...