单击两次相同的图标时无法切换

时间:2017-05-23 01:47:25

标签: javascript reactjs redux

我有3个图标供用户选择,他们可以选择多个图标,但如果点击相同的图标,则应切换。我的意思是当我点击Facebook图标和推特图标时,两个图标都应突出显示,但如果我再次点击脸书或推特图标则不应突出显示。突出显示正在工作但单击两次不会删除突出显示。

这是我的代码

const socialPlatforms = [
{ name: 'facebook', fontName: 'facebook-square', icon: 'facebook-icon' },
{ name: 'twitter', fontName: 'twitter-square', icon: 'twitter-icon' },
{ name: 'instagram', fontName: 'instagram', icon: 'instagram-icon' },
];

addPlatform = (platform) => {
this.props.selectPlatform(platform);
};


render() {
const { settings } = this.props;
console.log('settings', settings.platforms);
const socialPlatform = socialPlatforms.map((platform, index) =>
  <FontAwesome
    name={platform.fontName}
    key={index}
    className={`icon-pointer font-awesome-icons ${settings.platforms.indexOf(platform.name) === -1 ? '' : platform.icon}`}
    size="5x"
    onClick={() => { this.addPlatform(platform.name); }}
  />
);


export const addPlatform = (platform) => ({
  type: ADD_PLATFORM,
  platform,
});

const initialState = {
loading: false,
platforms: [],
};

export default(state = initialState, action) => {
switch (action.type) {
  case ADD_PLATFORM: {
    let index = state.platforms.indexOf(action.platform);
    if (index === -1) {
      return {
        ...state,
        platforms: [...state.platforms, action.platform],
      };
    }
    return {
      ...state,
      platforms: state.platforms.filter((localIndex) => localIndex !== index),
    };
  }
  default:
    return state;
}
};

我使用过滤器进行切换,但不能正常工作。

1 个答案:

答案 0 :(得分:0)

localIndex应该是filter callback的第二个参数。您正在使用第一个元素。