ADD_SONG未添加到播放列表

时间:2018-07-05 16:20:11

标签: reactjs redux react-redux

在我的应用中 有一个呈现(播放)列表的组件 (我有2个硬编码的列表) 我可以将新列表添加到列表列表中。 当您单击列表时 显示歌曲列表,列表的底部是 单击该按钮时,将显示带有输入(标题,艺术家,专辑)的表单。 在修复添加列表功能之前,歌曲已添加到“活动”列表中 但现在 动作被分派(ADD_SONG)并在(Redux)状态下以正确的值显示,但它呈现与列表相同类型的元素/组件,并且未添加/添加... 我不确定去哪里看 我希望有人能发现我的错误逻辑

AddSongForm

export default class AddSongForm extends React.PureComponent {
  constructor() {
      super();

      this.state = {
        clicked: false
      };

      this.handleClick = this.handleClick.bind(this)
    }

    handleClick() {
      this.setState({
        clicked: !this.state.clicked
      })
    }

  handleChange = (event) => {
    const value = event.target.value
    const name = event.target.name
// console.log(name, value)
// console.log(this.state);
    this.setState({
      [name]: value
    })
  }

  handleSubmit = (event) => {
    event.preventDefault()
console.log(this.state);
    if (this.state.title && this.state.artist) {
      this.props.addSong({
        title: this.state.title,
        artist: this.state.artist,
        album: this.state.album
      })
    }
  }

  render() {

    return (<div>
      <button onClick={this.handleClick}><h2>New Song+</h2></button>

  {this.state.clicked ?
     <form onSubmit={this.handleSubmit}>
        <label>
          Song Title:
          <input type="text" name="title" onChange={this.handleChange} />
        </label>
        <label>
        <br/>  Artist:
          <input type="text" name="artist" onChange={this.handleChange} />
        </label>
        <label>
        <br/>  Album:
          <input type="text" name="album" onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
      : null}
    </div>)
  }

}

AddSongFormContainer

import AddSongForm from './AddSongForm'
import { connect } from 'react-redux'

class AddSongFormContainer extends React.PureComponent {
  addSong = (song) => {
    this.props.dispatch({
      type: 'ADD_SONG',
      payload: {
        id: Math.ceil(Math.random()*10000),
        ...song
      }
    })
  }

  render() {

    return <AddSongForm addSong={this.addSong} />
  }
}

export default connect(null)(AddSongFormContainer)

具有初始状态的减速器

const initState = [

  {
    id: 1,
    title: 'Play list 1',
    data: [
      {
        id: 1,
        title: 'DogHeart II',
        artist: 'The Growlers',
        album: 'Gilded Pleasures'
      }, {
        id: 2,
        title: 'Beast of No nation',
        artist: 'Fela Kuti',
        album: 'Finding Fela'
      }, {
        id: 3,
        title: 'Satellite of love',
        artist: 'Lou Reed',
        album: 'Transformer'
      }
    ]
  }, {
    id: 2,
    title: 'Play list 2',
    data: [
      {
        id: 1,
        title: 'Whatever happend to my Rock and Roll',
        artist: 'BlackRebelMoterCycleClub',
        album: 'B.R.M.C'
      }, {
        id: 2,
        title: 'U Sexy Thing',
        artist: 'Crocodiles',
        album: 'CryBaby Demon/ U Sexy Thing'
      }, {
        id: 3,
        title: 'Oh Cody',
        artist: 'NoBunny',
        album: 'Raw Romance'
      }
    ]
  }
]
const reducer = (state = initState, action = {}) => {
  switch (action.type) {

    case 'ADD_LIST':
      return [
        ...state,
        action.payload
      ]
    case 'ADD_SONG':
      return [
        ...state,
        action.payload
      ]

    default:
      return state
  }
}

export default reducer

PlayList组件映射列表中的所有歌曲

export default class PlayList extends React.Component{
  constructor() {
      super()

      this.state = {
        clicked: false
      }
      this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
      this.setState({
        clicked: !this.state.clicked
      })
      console.log(this.props.selectList.name)

    }


render(){
  // console.log(this.props);
// console.log(this.props.playLists[0].data);
  return (<div>
    <button  onClick={this.handleClick}><h1>{this.props.playLists.title}</h1></button>
{this.state.clicked ?
  <ul>
      { this.props.playLists.data.map(song =>
        <li key={song.id} onClick={() => this.props.selectSong(song.id)}>
          <b>{song.title}</b><br/>
            By:
            <br/>
            <h3><b>{song.artist}</b></h3><br/>
             Appears on:
              <b>{song.album}</b><br/><br/>
        </li>
      ) }
      <AddSongFormContainer/>
    </ul>


     : null}


  </div>)
  }
}

初始状态(数组)中所有播放列表的容器

class PlayListsContainer extends React.PureComponent {


  selectSong = (id) => {
  this.props.dispatch({
    type: 'SELECT_SONG',
    payload: id
  })
}

  selectSong(id) {
    console.log('selected song:', id)
  }
  selectList = (id) => {
    this.props.dispatch({
      type: 'SELECT_LIST',
      payload: id
    })
  }

    selectList(id) {
      console.log('selected song:', id)
    }

    render() {
        const playlistsArray = this.props.playLists
        // console.log(playlistsArray)
        return (
            playlistsArray.map((playlist) => <PlayList
                playLists={playlist}
                selectSong={this.selectSong}
                selectList={this.selectList}
                key={playlist.id}
            />)

        )
    }








}

const mapStateToProps = (state) => {
// console.log(state.playLists);
  return {
    playLists: state.playLists



  }
}

export default connect(mapStateToProps)(PlayListsContainer)

redux state after submitting a new song

1 个答案:

答案 0 :(得分:1)

在您的评论中描述了您的redux问题,以及Redux开发工具的屏幕截图-问题现在很明显。

添加歌曲时,只需将其添加到商店的顶层,而无需将其实际添加到播放列表中。

完全有可能按原样解决此问题。在还原器中,您无需像现在那样添加歌曲,需要将其专门添加到播放列表中。如果您需要一个代码示例,我可以提供一个示例。

但是,我鼓励您重构您的redux存储-并遵循拥有normalized, flat state.

的最佳实践

这意味着,您要为redux存储区提供两个顶级对象。

playlists
songs

您只需引用歌曲的ID,而不是在播放列表中包含有关歌曲的所有数据即可。

您的播放列表如下:

playlists { 
  1: {
  title: 'my playlist'
  songs: [1,2,3]}

而且歌曲可以保持不变。

每当将歌曲添加到播放列表时,只需添加歌曲,然后使用新的歌曲ID更新播放列表。

您可以做的另一种做法是使用mapDispatchToProps,而不是定义内联的redux操作分派,以使代码更简洁。该文档为here.

要按原样修复代码,我们需要做的主要事情是传递您要添加歌曲的播放列表ID。否则,我们还怎么知道将歌曲放在哪里?

首先,在您的addSongFormContainer中更新您的操作,以接受其他参数targetPlaylist(这首歌将进入该参数)

  addSong = (song, targetPlaylist) => {
this.props.dispatch({
  type: 'ADD_SONG',
  payload: {
    playlist: targetPlaylist
    id: Math.ceil(Math.random()*10000),
    ...song
    }
  })
}

此操作的用法现在需要您传递目标播放列表。为简便起见,我将对这首歌曲已添加到播放列表1中进行硬编码。我将剩下将所选播放列表向下传递到组件的练习。

我还清理了handleSubmit,通过将歌曲也移入它自己的变量来使其更加清晰。

  handleSubmit = (event) => {
  event.preventDefault()
  console.log(this.state);

  if (this.state.title && this.state.artist) {

    let song = {
      title: this.state.title,
      artist: this.state.artist,
      album: this.state.album
    }
    let selectedPlayList = 1 //Fix this later :)
    this.props.addSong(song, selectedPlayList)
  }
}

现在最后一个问题是减速器。

case 'ADD_SONG':
      const index = store.getState().findIndex(playlist => playlist.id === 
        action.payload.playlist)
      console.log(index) //This should be index 0, after looking up playlist id: 1
      const updatedPlaylistSongs = this.state[index].data
      updatedPlaylistSongs.push(action.playload.song)
      return [
        ...state.slice(0, index), // All playlists before current
        {
          ...state[index], //The targeted playlist.
          ...updatedPlaylistSongs //The updated songs
        },
        ...state.slice(index + 1), //All playlists after current
    ]

我希望reducer为您工作,尽管它可能需要一些工作-我不习惯于编写处理数组的reducer。我通常具有规范化的数据,这使得修改起来容易得多。我强烈建议您尝试规范化Redux存储。停止使用数组,尝试使用生成密钥的对象(使用uuidv4生成唯一且随机的密钥)。这使得“选择”您想要编辑/更新的内容变得更加容易。

我希望这会有所帮助!