簡體   English   中英

當 redux 狀態更新時,React 組件不更新

[英]React component not updating when redux state is updating

我正在觸發一個動作來執行一些切換功能,但是,即使 redux 狀態是,我的反應組件也不會重新呈現

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

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

這里country.name === action.name ? {...country, visited: !country.visited} : country country.name === action.name ? {...country, visited: !country.visited} : country你正在搜索 action.name 的country.name === action.name ? {...country, visited: !country.visited} : country ,但在下面的聲明中你沒有給有效載荷一個正確的名字

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM