gpt4 book ai didi

javascript - react : Passing an object to state

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:23:58 24 4
gpt4 key购买 nike

我正在尝试使用 Spotify Web API 制作 Spotify Web Player 的副本。现在,我正在尝试使用 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;

最佳答案

您需要绑定(bind)上下文以便您可以访问该类。下面是它可能看起来像下面的片段。为了便于阅读,我分解了逻辑。

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

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;

还要确保在构造函数中绑定(bind) setActivePlaylist 或使其成为箭头函数

关于javascript - react : Passing an object to state,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54471678/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com