当Redux状态更新时,React组件未更新

时间:2019-01-19 16:59:14

标签: javascript reactjs

我正在触发动作以执行某些切换功能,但是,即使redux状态为,我的react组件也不会重新呈现

const Countries = ({ countries, toggleCountry }) => (
  <div>
    <h4> All Countries </h4>
    <div className="container">
      {countries.map((country, index) => (
        <div
          key={index}
          className={`countryContainer ${country.visited ? 'visited' : ''}`}
        >
          <img src={country.flag} alt="countryFlag" />
          <p className="countryName"> {country.name} </p>
          <button onClick={() => toggleCountry(country.name)}>
            {country.visited ? 'undo' : 'visited'}
          </button>
        </div>
      ))}
    </div>
  </div>
);

const mapStateToProps = ({ countries }) => ({
  countries
});

const mapDispatchToProps = dispatch =>
  bindActionCreators(
    {
      toggleCountry
    },
    dispatch
  );

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Countries);

当我单击此按钮时,它可以在redux状态下正确切换,但是该组件不会重新呈现以显示新的按钮标签或更改类名

这是我的减速器

const initialState = []

export default(state = initialState, action) => {
  switch(action.type){
    case 'UPDATE_INITIAL_COUNTRIES':
      return state.concat(action.countries)
    case 'UPDATE_COUNTRY_VISITED':
      return state.map(country => (
        country.name === action.name ? {...country, visited: !country.visited} : country
      ))
    default:
      return state;
  }
}

和我的动作创建者

export const toggleCountry = countryName => {
  return dispatch => {
    dispatch({ type: 'UPDATE_COUNTRY_VISITED', countryName })
  }
}

2 个答案:

答案 0 :(得分:0)

该操作期望action.name,但收到action.countryName

问题在这里

export const toggleCountry = countryName => {
  return dispatch => {
    dispatch({ type: 'UPDATE_COUNTRY_VISITED', countryName })
  }
}

修复:

export const toggleCountry = name => {
  return dispatch => {
    dispatch({ type: 'UPDATE_COUNTRY_VISITED', name })
  }
}

答案 1 :(得分:0)

这里country.name === action.name ? {...country, visited: !country.visited} : country 你正在搜索 action.name 但在下面的声明中你没有给有效载荷一个正确的名字

export const toggleCountry = countryName => {
      return dispatch => {
        dispatch({ type: 'UPDATE_COUNTRY_VISITED', countryName })
      }
    }

修复:

export const toggleCountry = countryName => {
      return dispatch => {
        dispatch({ type: 'UPDATE_COUNTRY_VISITED', name :countryName })
      }
    }
相关问题