反应:将对象传递给状态

时间:2019-02-01 01:28:15

标签: javascript reactjs spotify

我尝试使用Spotify的网络API,使Spotify的网络播放器的翻版。现在,我正在尝试设置与onClick事件处理程序activePlaylist。但是,当我将播放列表对象传递给事件处理程序方法时,该对象是未定义的。我已经尝试修复了很长时间。你有什么建议吗?

注意:它将名称正确映射到页面,但是当我将其传递给事件处理程序方法时,该对象变为未定义。

这是我的代码:

import React, { Component } from 'react';
import '../css/playlists.css';

class Playlists extends Component {
  constructor(props) {
    super(props);

    this.state = {
      activePlaylist: null
    };
  }

  setActivePlaylist(playlist) {
    console.log('From setActivePlaylist');
    console.log(playlist.name); //this logs as undefined
  }

  render() {
    const {playlists} = this.props;

    return(
      <div className='playlists'>
        <h4 id='playlist-label'>Playlists</h4>
        {this.props.playlists
          ?
          (this.props.playlists.items.map((playlist, index)=>
            <a href="#" onClick={(playlist) => this.setActivePlaylist(playlist)}>
              <h4
              key={index}
              >
                {playlist.name}
              </h4>
            </a>
          ))
          :
          (<h4>Loading playlists...</h4>)
        }
      </div>
    );
  }
}

export default Playlists;

1 个答案:

答案 0 :(得分:1)

您将希望绑定上下文,以便可以访问该类。这就是下面的内容。我只是为了提高可读性而打破了逻辑。

此外,您尝试使用与传入变量相同的名称覆盖事件的参数-因此,“播放列表”是事件对象,而不是您期望的对象”

onClick={/* this be no good-->*/ (**playlist**) => this.setActivePlaylist(playlist)}

您可以在此处查看演示: https://stackblitz.com/edit/react-passing-an-object-to-state?file=Playlists.js

import React, { Component } from 'react';

class Playlists extends Component {

  constructor(props) {
    super(props);

    this.state = {
      activePlaylist: null
    };

    // Need to bind the scoped context so we have access to "Playlists" component.
    this.renderLink = this.renderLink.bind(this);
  }

  setActivePlaylist(playlist) {
    console.log('From setActivePlaylist');
    console.log(playlist.name);
  }

  render() {
    const {items} = this.props.playlists

    return(
      <div className='playlists'>
        <h4 id='playlist-label'>Playlists</h4>
        {items
          ? items.map(this.renderLink)
          : <h4>Loading playlists...</h4>
        }
      </div>
    );
  }

  renderLink(playlist, index) {
    return (
      <a onClick={() => this.setActivePlaylist(playlist)}>
        <h4 key={index}>
            {playlist.name}
          </h4>
        </a>
    );
  }
}

export default Playlists;

还要确保将setActivePlaylist绑定到构造函数中或使其变为箭头功能