reactjs - 在两个组件之间来回移动列表项

时间:2017-07-04 23:10:05

标签: reactjs

我正在努力学习ReactJS。我正在进行API调用以显示iTunes中的列表,当单击单个列表项时,它们会移动到新列表(类似于队列)。当在新列表中单击时,它们将移回原始列表,但是当列表项移回时,列表项不会从新列表中删除。这是我的问题的一个方面:https://jsfiddle.net/6k9ncbr6/

class App extends React.Component {
constructor(props) {
    super(props);

    this.state = {
            searchResults: [],
            moveResults: []
    }

    this.handleEvent = this.handleEvent.bind(this);
}

showResults = (response) => {
    this.setState({
        searchResults: response.results,
        moveResults: []
    })
}

search = (URL) => {
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: URL,
        success: function(response) {
            this.showResults(response);
        }.bind(this)
    });
}

handleEvent = (clickedTrack) => {
    const { searchResults, moveResults } = this.state;
    const isInSearchResults = searchResults.some(result => result.trackId === clickedTrack.trackId);

    this.setState({
        searchResults: isInSearchResults ? searchResults.filter(i => i.trackId  !== clickedTrack.trackId) : [...searchResults, clickedTrack],
        moveResults: isInSearchResults ? [...moveResults, clickedTrack] : moveResults.filter(i => i.trackId !== clickedTrack)
    });
}

componentDidMount() {
    this.search('https://itunes.apple.com/search?term=broods');
}

render(){
    return (
        <div>
            <Results 
              searchResults={this.state.searchResults} 
              handleEvent={this.handleEvent}/>
            <Results 
              searchResults={this.state.moveResults} 
              handleEvent={this.handleEvent} />
        </div>
    );
  }
}
class Results extends React.Component {
  render(){
    const { handleEvent, searchResults } = this.props;
    return(
        <ul>
            {this.props.searchResults.map((result, idx) => 
                    <ResultItem 
                 key={`${result.trackId}-${idx}`} 
                 trackName={result.trackName} 
                 track={result}
                 handleClick={handleEvent} />
                    )}
        </ul>
    );
  }
}

  class ResultItem extends React.Component {
     render(){
        const { handleClick, track, trackName } = this.props
    return <li onClick={() => handleClick(track)}> {trackName} </li>;
   }
 }

ReactDOM.render(
   <App />, document.getElementById('root')
);

1 个答案:

答案 0 :(得分:2)

你留下了一个属性名称:

moveResults: isInSearchResults ? [...moveResults, clickedTrack] : moveResults.filter(i => i.trackId !== clickedTrack.trackId)

clickedTrack.trackId缺少现有代码中的.trackId

这是working jsFiddle