您编写的大多数代码都是正确的,如果您希望在调用操作后立即看到更新的输出,那么它将无法正常工作
onGetCountryById(id) {
this.props.fetchCountryById(id);
console.log(this.props.country); // This will gives you the current country (We just update the state, but still that value didn't update the component)
}
尝试在下面的 html 中打印国家/地区的值,您会看到它正在更新
{this.props.country === null ? "default" : this.props.country.name}
在减速器中,您可能需要进行此更改
case CountryActions.FETCH_COUNTRY_BY_ID:
return {
...state,
country: state.countries.find((item) => item.id === action.id) // use find instead of filter
};
并将国家的初始值设置为null
const initCountriesState = {
country: null,
countries: [
....
]
};
这是更新的沙箱