我从使用React映射的API中获取列表项中的特定数据时遇到了一些困难。
在我的渲染中,我在艺术家列表上进行映射,并在此基础上呈现艺术家姓名,歌曲名称和乐谱的URL:
render(){
return(
<div className="songContainerOuter">
{this.props.artist.map((artist, i) => {
return (
<div className="songContainerInner" key={i}>
<ul>
<div className="leftSide">
<li ref={ref => this.artistName = ref}>{artist}</li>
</div>
<div className="rightSide">
<div className="topRight">
<li ref={ref => this.songTitle = ref}>{this.props.title[i]}</li>
</div>
<div className="bottomRight">
<li ref={ref => this.songUrl = ref}><a href={`${this.props.link[i]}`}><i className="fas fa-link"></i></a></li>
<li onClick={this.addFavourite}><i className="fas fa-plus"></i></li>
</div>
</div>
</ul>
</div>
)
})}
</div>
)
}
然后点击一个加号图标的li,我想将值存储在每个单独渲染的div中。我遇到的问题是,当我点击添加按钮时,在我的控制台日志中我将获得所有数据以及完全相同的歌曲,艺术家和URL,无论哪个映射div添加按钮I& #39;点击:
addFavourite(e){
e.preventDefault();
const favs ={
artist: this.artistName.textContent,
title: this.songTitle.textContent,
url: this.songUrl.textContent.outerHTML,
};
const newFavs = Array.from(this.state.favourites);
newFavs.push(favs);
this.setState({
favourites: newFavs
})
console.log(this.state.favourites)
}
是否有另一种方法可以在li标签中存储值,并且只在每个映射的div中存储唯一值?
答案 0 :(得分:1)
请尝试以下方法。如果您想检查您的状态是否正确更新,请参阅@Ved answer。
addFavourite(artist, songIndex){
const fav = {
artist,
title: this.props.title[songIndex],
url: this.props.link[songIndex]
};
const newFavs = Array.from(this.state.favourites);
newFavs.push(favs);
this.setState({
favourites: newFavs
});
}
render(){
return (
<div className="songContainerOuter">
{this.props.artist.map((artist, i) => {
const { link, title } = this.props;
return (
<div className="songContainerInner" key={i}>
<ul>
<div className="leftSide">
<li>{artist}</li>
</div>
<div className="rightSide">
<div className="topRight">
<li>{title[i]}</li>
</div>
<div className="bottomRight">
<li><a href={`${link[i]}`}><i className="fas fa-link"></i></a></li>
<li onClick={event => this.addFavourite(artist, i)}><i className="fas fa-plus"></i></li>
</div>
</div>
</ul>
</div>
)
})}
</div>
)
}
答案 1 :(得分:0)
@anbhd,您可以进行以下更改并进行测试:
将以下部分添加到constructor
部分:
constructor(props) {
super(props);
this.addFavourite = this.addFavourite.bind(this);
}
addFavourite(artist) {
console.log(artist)
}
并更改onClick
功能,如下所示:
<li onClick={this.addFavourite(artist)}><i className="fas fa-plus"></i></li>
答案 2 :(得分:0)
问题是你正试图在setState
之后获取数据。 setState是async
操作,因此您将获得旧数据。尝试将日志放在setState回调中。
addFavourite(e){
e.preventDefault();
const favs ={
artist: this.artistName.textContent,
title: this.songTitle.textContent,
url: this.songUrl.textContent.outerHTML,
};
const newFavs = Array.from(this.state.favourites);
newFavs.push(favs);
this.setState({
favourites: newFavs
},()=>{
console.log(this.state.favourites)//inside setState callback
})
}