我正在执行操作以执行某些切换功能,但是,即使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 })
}
}
最佳答案
该动作期望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 })
}
}