【发布时间】:2020-03-04 21:29:01
【问题描述】:
我有以下情况:
我的应用状态中国家/地区列表的选择器
export const getCountries = state => state.countries;
还有一个使用 reselect 创建的选择器来过滤具有特定 id 的国家/地区
export const getCountryById = countryId =>
createSelector(
[getCountries],
(countries) => {
let countriesList = countries.filter(c => c.id === countryId);
if ( countriesList ) {
return countriesList[0];
}
return null;
}
)
然后有一个国家详情页面组件(通过http://localhost:3000/country/4 访问)
import React from 'react';
import { getCountryById } from '../redux/selectors';
import { connect } from 'react-redux';
const CountryPage = ({country}) => {
return <h1>{country.name}</h1>
}
const mapStateToProps = (state, ownProps) => {
console.log(ownProps.match.params.countryId);
const obj = {
country: getCountryById(ownProps.match.params.countryId)
}
return obj;
};
export default connect(mapStateToProps, null)(CountryPage);
mapStateToProps 正确接收 countryId,但未调用选择器。我在这里想念什么?
或者它是使用选择器的错误方法?我知道我可以在 CountryPage 中使用州的完整国家/地区列表并在那里进行过滤,但是这里的最佳做法是什么?
【问题讨论】: