我正在触发一个操作来执行一些切换功能,但是,即使 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/