从列表视图保存数据的正确方法是什么? [英] What is the right way to save data from a list view?
问题描述
我有一个SearchPage组件执行查询,然后在列表视图中显示结果。然后,用户通过点击它们来选择他们想要的结果。这将它们保存到SearchResults组件中的数组。
I have a SearchPage component that performs a query and then displays the results in a list view. The user then selects which of the results that they want by tapping on them. This saves them to an array in the SearchResults component.
如下面的代码所示,当返回结果时调用'displayWords'方法。它在堆栈上推送一个新视图,SearchResults,设置正确的按钮为保存,并附加一个要调用的函数,希望保存数据。
As seen in the code below, the 'displayWords' method is called when the results are returned. It pushes a new view on the stack, SearchResults, sets the right button to "Save", and attaches a function to be called which wants to save the data.
class SearchPage extends Component {
displayWords(words) {
this.props.navigator.push({
title: 'Results',
component: SearchResults,
rightButtonTitle: 'Save',
onRightButtonPress: () => {this.props.navigator.pop();
this.props.save()},
passProps: {listings: words}
});
this.setState({ isLoading: false , message: '' });
}
这里是问题,如何从SearchResults组件中的数组中获取项目到回调?还是到SearchPage?
So here is the question, how do I get the items from the array in the SearchResults component into the callback? Or to the SearchPage? Or is there another pattern that I should be following?
推荐答案
有趣的问题!
从哲学上讲,整个导航器和导航堆栈概念都打破了React-y数据流。因为如果您可以将 SearchResults
组件简单地渲染为 SearchPage
的子组件,那么您只需将选定的搜索结果成为 SearchPage
状态的一部分,并将其作为道具传递给 SearchPage
。 SearchPage
也会在搜索结果切换时获得回调以通知 SearchResults
。
Philosophically speaking, the whole navigator and navigation stack concept kind of breaks the React-y dataflow. Because if you could render the SearchResults
component simply as a subcomponent of SearchPage
, you'd just make the selected search results be part of the SearchPage
state and pass them into SearchPage
as props. SearchPage
would also get a callback to notify SearchResults
whenever a search result was toggled.
唉,导航器是什么,你必须复制这个状态。
Alas, with the navigator being what it is, you're going to have to duplicate the state.
displayWords(words) {
this.props.navigator.push({
title: 'Results',
component: SearchResults,
rightButtonTitle: 'Save',
onRightButtonPress: () => {this.props.navigator.pop();
this.props.save()},
passProps: {listings: words, onWordToggle: this.onWordToggle}
});
this.setState({ isLoading: false , message: '' });
}
onWordToggle(word) {
// add or remove 'word' from e.g. this._selectedWords; no need for
// this.state because re-rendering not required
}
而 SearchResults
会在其 this.state
中保留所选字词的列表,只需通知
while SearchResults
would maintain the list of selected words in its this.state
and simply notify this.props.onWordToggle
whenever a word is added or removed.
这篇关于从列表视图保存数据的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!