我是React的新手。我正在显示歌曲列表,我希望允许用户将歌曲添加到他们的收藏夹中。我使用Redux来存储喜欢的歌曲。我的PlayList组件如下所示:
import AddSong from '../containers/AddSong'
class Playlist extends Component {
render(){
return (
<div>
<h1>Playlists</h1>
<ul className="container">
{this.state.items.map(item =>
<li key={item.track.id}>
{item.track.name} by {item.track.artists[0].name}
<img src={item.track.album.images[0].url} height="150" width="150" />
<AddSong title={item.track.name} />
</li>
)}
</ul>
</div>
);
}
...
}
所以我将歌曲名称传递给AddSong <AddSong title={item.track.name} />
AddSong看起来像:
import React from 'react'
import { connect } from 'react-redux'
import { addSong } from '../actions'
let AddSong = ({ dispatch }) => {
let input
console.log('this is ', this);
return (
<div>
<form
onSubmit={e => {
e.preventDefault()
// GET SONG FROM PROPS AND DISPATCH
//dispatch(addSong(input.value))
}}
>
<input
ref={node => {
input = node
}}
/>
<button type="submit">
Add Song
</button>
</form>
</div>
)
}
AddSong = connect()(AddSong)
export default AddSong
但是,this
是具有属性的对象:
{
a: Connect(props, context)
}
如何在AddSong中获得歌曲名称?
修改
所以这就是我现在所拥有的,我在这里将歌曲标题传递给AddSong:
<AddSong song={item.track.name} title={item.track.name} />
我将歌曲标题作为歌曲和标题传递,以显示会发生什么。
在AddSong中,我有:
const mapStateToProps = (state) => {
const {song:song} = state; // or whatever the reducer called
return {song};
};
const mapDispatchToProps = (dispatch) => ({
addSong: (value) => dispatch(addSong(value)),
});
export default connect(mapStateToProps, mapDispatchToProps)(AddSong);
在AddSong的顶端,我正在做:
let AddSong = ({ dispatch, ...props }) => {
let input
console.log('props is ', props);
控制台输出:
props is Object {song: undefined, title: "Young Blood"}
我已将按钮更改为:
<button onClick={(value)=>props.addSong(value)}>
Add Song
</button>
当我点击时,会出现错误:
Failed prop type: Invalid prop `songs[0].text` of type `object` supplied to `SongList`, expected `string
答案 0 :(得分:0)
尝试使用此功能
const mapStateToProps = function(store) {
return {
data: store.data
};
}
AddSong = connect(mapStateToProps)(AddSong)
答案 1 :(得分:0)
我假设您有减速器,并且您想通过道具访问该状态,如果是这种情况,您可以mapStateToProps,例如。
const mapStateToProps = (state) => {
const {song:song} = state; // or whatever the reducer called
return {song};
};
const mapDispatchToProps = (dispatch) => ({
addSong: (value) => dispatch(addSong(value)),
});
export default connect(mapStateToProps, mapDispatchToProps)(AddSong);
然后你可以写this.props.song
。