javascript - 当 redux 状态更新时,React 组件不更新

标签 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 状态下正确切换,但组件不会重新渲染以显示新按钮标签或更改类名称

这是我的 reducer :

常量初始状态=[]

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

和我的 Action 创建者

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

最佳答案

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

关于javascript - 当 redux 状态更新时,React 组件不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54269357/

相关文章:

javascript - 是否有用于 jQuery 的移动触摸事件插件?

javascript - 当用户在上面的输入 div 中键入文本并使其更高时,缩短 div 的高度

javascript - 在新的 React 图表中使用从 Highcharts 编辑器导出的数据

reactjs - 如何将 store 作为 prop 显式传递给 "Connect()"

reactjs - 为什么我在创建 React 应用程序时出错?

javascript - 此代码不起作用//CSS 定位快把我逼疯了。从来没有这么困难

javascript - 你能用 Javascript 从 iPhone 上的网络摄像头捕获图像吗?

javascript - 这是什么网络效果

javascript - react : How mock functions and test component rendering with jest:

javascript - 在对象上 react 映射,然后在数组上 react