【问题标题】:React component not updating when redux state is updating当 redux 状态更新时,React 组件不更新
【发布时间】:2019-06-13 15:02:09
【问题描述】:

我正在触发一个动作来执行一些切换功能,但是,即使 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 状态,但组件不会重新渲染以显示新按钮标签或更改类名

这是我的减速器:

常量初始状态 = []

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 })
  }
}

【问题讨论】:

  • 你能显示你的toggleCountry动作创建者代码吗?
  • @VuHuuCuong 完成
  • 还有相应的reducer :)
  • @VuHuuCuong 也完成了
  • 翻转清酒,修复它。使用name 而不是`countryName` facepalm

标签: javascript reactjs


【解决方案1】:

该操作需要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 })
  }
}

【讨论】:

    【解决方案2】:

    这里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 })
          }
        }
    

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 1970-01-01
      • 2016-10-02
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-18
      相关资源
      最近更新 更多