.map函数中的if / else反应

时间:2019-03-05 15:31:14

标签: reactjs

我有个问题。我必须构建一个应用程序,使人们可以从“ lastFm”搜索音乐。到目前为止,到目前为止,我已经做出了一些事情可以正常工作,但是我对map函数中的if / else有问题,我试图向用户显示“找不到结果”(如果有),但是没有运气。屏幕上将显示1+个结果,但是如果有任何结果,则什么也不会发生。这是我的代码。

import React, { Component } from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';

import {
  TextField,
  Button,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  Avatar,
  Card,
  CardContent
} from '@material-ui/core';
import axios from 'axios';

import './App.css';

const API_URL = 'http://ws.audioscrobbler.com/2.0/?limit=5&format=json&method=artist.search&api_key=' + process.env.REACT_APP_LASTFM_APPKEY;

const isEmpty = (str) => str.length === 0;
class App extends Component {
  state = {
    searchTerm: '',
    savedArtists: []
  }

  componentDidMount() {
    const existing = localStorage.getItem('savedArtists')
    if (existing) {
      this.setState({ savedArtists: JSON.parse(existing) })
    }
  }

  onTextChange = (event) => {
    const value = event.target.value;

    this.setState({ searchTerm: value });
  }

  search = (terms) => {
    const request = API_URL + '&artist=' + terms;

    axios.get(request).then((response) => {
      const results = response.data.results;
      const artists = results.artistmatches.artist.map((artist) => {
        const avatarImage = artist.image.find(image => image.size === 'medium');
        const imageUrl = avatarImage['#text'];
        return { ...artist, avatar: imageUrl }
      });

      this.setState({ artists });
    })
  }

  onSearchClick = () => {
    this.search(this.state.searchTerm);
  }

  clearSearch = () => {
    this.setState({
      searchTerm: '',
      artists: []
    })
  }

  onResultClick = (artist) => {
    this.clearSearch();
    const savedArtists = this.state.savedArtists;
    savedArtists.push(artist)
    this.setState({ savedArtists: savedArtists })
    localStorage.setItem('savedArtists', JSON.stringify(savedArtists));
  }

  render() {
    const results = this.state.artists || [];
    return (
      <div className="App">
        <header className="App-header">
          <AppBar position="static" color="primary">
            <Toolbar className="search-bar">
              <Typography variant="h6" color="inherit">
                Photos
              </Typography>
              <TextField
                placeholder="Search on Last.fm"
                className="search-input"
                onChange={this.onTextChange}
                value={this.state.searchTerm}
              />
              <Button
                onClick={this.onSearchClick}
                variant="contained"
                color="secondary"
                disabled={isEmpty(this.state.searchTerm)}
              >
                Search
              </Button>
              {!isEmpty(this.state.searchTerm) && (
                <Button
                  onClick={this.clearSearch}
                  variant="contained"
                >
                  Clear
                </Button>)
              }
            </Toolbar>
          </AppBar>
        </header>
//****Here is  where i've try to use if/else
        <List className="search-results">
          {
            results.map((artist ,results) => {
              if(results.length === 0)

              return (<ListItem> Not Found</ListItem>

              ); else {
                return (                <ListItem
                  button
                  key={artist.name}
                  className="result"
                  onClick={() => this.onResultClick(artist)}
                >
                  <ListItemAvatar>
                    <Avatar src={artist.avatar} alt={artist.name} />
                  </ListItemAvatar>
                  <ListItemText primary={artist.name} />
                  <Button
                    variant="outlined"
                    color="secondary"
                    size="small"
                    className="add-button"
                  >
                    Add to favorites
                  </Button>
                </ListItem>);
              }


            })

          }
        </List>
        <div className="artist-container">
          {
            this.state.savedArtists.map((artist, i) => {
              return (
                <Card className="artist-card"
                  key={i}
                >
                  <CardContent>
                    {artist.name}
                  </CardContent>
                </Card>
              )
            })
          }
        </div>
      </div>
    );
  }
}

export default App;

2 个答案:

答案 0 :(得分:1)

您在这里遇到错误。它是.map(result: any, index: number, original: []),因此您要使用参数results来引用索引号:

results.map((artist, results) => {
  if(results.length === 0) { ... }
});

因此,只需不将results用作.map的参数就可以解决此问题

答案 1 :(得分:0)

问题是您要在数组的映射中执行if / else。但是,如果数组中没有项目,则没有任何映射。

要做的是使用三元数检查数组是否有任何结果:

{ results && result.length ? 
    <List className="search-results">
            {
                results.map((artist) => {
                    return ( 
                    <ListItem button key={artist.name} className="result" onClick={() => this.onResultClick(artist)} >
                        <ListItemAvatar>
                            <Avatar src={artist.avatar} alt={artist.name} />
                        </ListItemAvatar>
                        <ListItemText primary={artist.name} />
                        <Button
                            variant="outlined"
                            color="secondary"
                            size="small"
                            className="add-button"
                        >
                            Add to favorites
                        </Button>
                    </ListItem>
                    );
                })
            }
    </List>
    : <div>No Results</div>
}

在这里,我们正在检查results.length是否正确,如果它是1或更高,它将显示您的列表,否则将显示div通知用户没有结果,您可以将其更改为所需的任何内容。