0

我正在用 React 做一个项目。这个想法是,当您搜索艺术家时,会在 pg 上渲染一个 img。单击图像后,将呈现协作艺术家的列表。然后,您可以单击一个名称并查看该人合作艺术家。这是我的问题:不是每次单击新艺术家时都会清除/重置状态,而是新艺术家只是添加到原始状态。有人可以帮我弄清楚如何清除状态,以便状态清除并返回新的协作者列表吗?被困在这几个小时了。这是代码

searchForArtist(query) {
    request.get(`https://api.spotify.com/v1/search?q=${query}&type=artist`)
      .then((response) => {
        const artist = response.body.artists.items[0];
        const name = artist.name;
        const id = artist.id;
        const img_url = artist.images[0].url;
        this.setState({
          selectedArtist: {
            name,
            id,
            img_url,
          },
        });
      })
      .then(() => {
        this.getArtistAlbums();
      })
      .catch((err) => {
        console.error(err);
      });
  }

  getArtistCollabs() {
    console.log('reached get artist collab function');
    const { artistCounts } = this.state;
    // console.log(artistCounts);
    const artist = Object.keys(artistCounts).map((key) => {
       //kate
      const i = document.createElement("div");
      i.innerHTML = key;
      i.addEventListener('click', () => {
        this.searchForArtist(key);
      })
      document.getElementById("collabs").appendChild(i);
    });
    this.setState({});
  }
  //kate
  renderArtists() {
    const artists = this.getArtistCollabs();
  }


  render() {
    const img_url = this.state.selectedArtist.img_url;
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input type='text' name='searchInput' className="searchInput" placeholder="Artist" onChange={this.handleChange} />
          <input type='submit' className="button" />
        </form>
          <img className="artist-img" src={this.state.selectedArtist.img_url}
          // kate
           onClick={this.renderArtists} alt="" />
          <div id="collabs">
          </div>
      </div>
4

1 回答 1

0

你的问题就在这里:

const artist = Object.keys(artistCounts).map((key) => {
  //kate
  const i = document.createElement("div");
  i.innerHTML = key;
  i.addEventListener('click', () => {
    this.searchForArtist(key);
  })
  document.getElementById("collabs").appendChild(i);

您在这里所做的是手动创建 html 元素并将它们插入到 dom 中。一旦发生这种情况,react 就无法控制这些新创建的元素。仅在绝对必要时才应该像这样操作 DOM。相反,您应该创建一个名为<ArtistCollaborators> 的新组件,它应该将艺术家作为道具,并使用自己的渲染方法将您在此处的代码渲染到 DOM 中。

这将是 React 的做法,并允许 react 完全控制您正在渲染到 DOM 中的内容。

于 2016-11-04T16:32:33.603 回答