What is the right way to save data from a list vie

2019-07-21 06:38发布

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.

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: '' }); 
   }
   

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?

1条回答
做个烂人
2楼-- · 2019-07-21 07:13

Interesting question!

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
   }

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.

查看更多
登录 后发表回答