按下返回按钮后无法删除项目

时间:2019-04-26 04:46:55

标签: redux

我正在国家应用程序项目中使用Redux,每当我按下后退按钮并尝试删除一些已保存的可比较国家/地区时,它都不会执行任何操作。

以下是gif表示形式:

enter image description here

您可以在gif表示中看到,我勾选了5个国家/地区,并删除了2个(在同一屏幕上),效果很好。但是当我按下 Compare 按钮并删除 Albania 时,该国家/地区并未删除。

我转到了Google Chrome的Redux开发工具,它显示删除操作未更改(状态相同),我不知道为什么要这么做。

这是我的代码:

排渣剂

const flagsInitialState = {
    compare: false,
    compareCountries: [],
    countryChecked: new Map()
}

export default ( state = flagsInitialState, action ) => {
    switch( action.type ) {
        case 'COMPARE_MODE':
            return {
                ...state,
                compare: ! state.compare
            }
        case 'ADD_COUNTRY_TO_COMPARE':
            return {
                ...state,
                compareCountries: [ ...state.compareCountries, action.country ]
            }
        case 'REMOVE_COUNTRY_TO_COMPARE': // <-- This is the action that does not remove an item when the back button is pressed
            return {
                ...state,
                compareCountries: state.compareCountries.filter( compareCountry => compareCountry !== action.country )
            }
        case 'SET_COUNTRY_MAPPING':
            return {
                ...state,
                countryChecked: state.countryChecked.set( action.name, action.checked )
            }
        default:
            return state
    }
}

标志动作

export const switchCompareMode = () => ({
    type: 'COMPARE_MODE'
})

export const addCountryToCompare = country => ({
    type: 'ADD_COUNTRY_TO_COMPARE',
    country
})

export const removeCountryToCompare = country => ({
    type: 'REMOVE_COUNTRY_TO_COMPARE',
    country
})

export const setCountryMapping = ( name, checked ) => ({
    type: 'SET_COUNTRY_MAPPING',
    name,
    checked
})

CountriesPage.jsx

const onCompareClick = ( country, e ) => {
        const checked = e.target.checked
        const name = e.target.name
        props.dispatch( setCountryMapping( name, checked ) )
        if ( props.countryChecked.get( name ) ) {
            props.dispatch( addCountryToCompare( country ) )
        } else {
            props.dispatch( removeCountryToCompare( country ) )
        }
    }

1 个答案:

答案 0 :(得分:0)

经过深思熟虑,我终于解决了这个问题!我只需要比较国家名称​​ strings 而不是国家 objects

case 'REMOVE_COUNTRY_FROM_COMPARE':
  return {
    ...state,
    compareCountries: state.compareCountries.filter( compareCountry => compareCountry.name !== action.country.name )
  }

无论如何,谢谢大家的帮助!