繁体   English   中英

如何使用redux选择列表项?

[英]How to select list item using redux?

我正在尝试从播放列表中选择一首歌,但是选择不能正常工作,因为当我第一次点击它时,当我第二次点击它选择一个项目时,它会返回“null”,但是某些原因,当我一直点击不同的项目时,我总是得到一个以前的项目值,我不知道为什么。

//Here is my action from redux:

import {FETCH_PLAYLIST_SUCCESS, FETCH_PLAYLIST_FAILURE, FETCH_PLAYLIST_REQUEST, SELECT_TRACK} from './types'
import {PREV, PLAY, PAUSE, NEXT, TOGGLE_TRACK} from './types';
import axios from "axios/index";

export const getPlayList = id => {
  return function (dispatch) {
    dispatch({type: FETCH_PLAYLIST_REQUEST});
    axios.get('https://cors-anywhere.herokuapp.com/https://api.deezer.com/search/track?q=red+hot+chili+peppers').then(response => {
      dispatch({
        type: FETCH_PLAYLIST_SUCCESS,
        payload: {
          playlist: response.data.data,
          currentTrack: response.data.data[0]
        }
      });
    }).catch(err => {
      dispatch({
        type: FETCH_PLAYLIST_FAILURE,
        payload: err,
      });
    })
  }
};

//func which takes index of list item
export  const selectTrack = (i) =>{
  return function (dispatch) {
    dispatch({
      type: SELECT_TRACK,
      payload: i
    });
  }
}

//reducer
 case SELECT_TRACK:
      return {
        ...state,
        selectedTrack: state.playList[action.payload],
      };

//click handler in container component
 handleClick = (index) => {
    this.props.selectTrack(index);
    console.log(this.props.playlist.selectedTrack);
    console.log(index);
  };

//how I'm using it in playlist component
<Playlist handleClick={this.handleClick} tracks={this.props.playlist.playList}/>

//Playlist component 
function PlayList(props) {
  const {i,handleClick,currentSongIndex,tracks,isSelected,} = props;
  return (
    <div className="playlist-container">
      <div className="playlist">
        <ul>
          {
            tracks.map((track, index) => (
              <Track
                isSelected={isSelected}
                index={index}
                key={track.id}
                id={track.id}
                title_short={track.title}
                duration={track.duration}
                clickHandler={ () => handleClick(index)}
              />
            ))
          }
        </ul>
      </div>
    </div>
  );
}

了解它在屏幕截图中的工作原理 在此输入图像描述

在此输入图像描述

在此输入图像描述

单击项目后,您将在容器的单击处理程序中分派操作。 console.log时处理程序中的道具仍然是旧道具。 只有redux更新状态和组件通过反应生命周期方法更新其道具时,新道具才会到达。

我猜你没有在reducer中设置任何初始状态,这可能是第一个值为null的原因。

尝试在render方法中添加相同的语句: console.log(this.props.playlist.selectedTrack) 你应该看到更新的道具

@Easwar是正确的(上图)您的调试逻辑是有问题的。

关于核心问题,我看不到你的一些重要道具传入的地方。你有:

const {i,handleClick,currentSongIndex,tracks,isSelected,} = props;

在您的PlayList组件中,但您正在调用它:

<Playlist handleClick={this.handleClick} tracks={this.props.playlist.playList}/>

currentSongIndexisSelected在哪里传入? 你可能遇到麻烦。 看起来他们将在<Playlist>的渲染方法中评估为null

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM