假设我有一个名为 Forecast 的最智能组件,它看起来像这样:
function mapStateToProps(state) {
return {
dates: state.getIn(['forecast', 'dates']),
isFetching: state.getIn(['forecast', 'isFetching'])
};
}
export default connect(mapStateToProps, {
fetchForecast
})(Forecast));
它包装了一个这样的预测组件:
import { getSummary, getDayForecast } from '../selectors/selectors';
export default class Forecast extends Component {
render() {
const { dates, isFetching } = this.props;
return (
<div className="row">
{dates.map(date => (
<Weather
key={date}
date={date}
getSummary={getSummary}
getDayForecast={getDayForecast}
/>
))}
</div>
);
}
};
在这里,我将 2 个选择器作为道具传递给一个Weather
组件。选择器如下所示:
import { createSelector } from 'reselect';
import moment from 'moment';
import { fromJS } from 'immutable';
const getDay = (state, key) => state.getIn(['forecast', 'forecast']).find(x => x.get('id') === key);
export const getSummary = createSelector(
[getDay],
(day => {
const firstPeriod = day.get('periods').first();
return fromJS({
date: day.get('date'),
outlook: firstPeriod.get('outlook'),
icon: firstPeriod.get('icon')
});
})
);
export const getDayForecast = createSelector(
[getDay],
(day) => day.get('periods').map(period => fromJS({id: period.get('id') }))
);
我不必将这些选择器作为道具向下传递,我可以轻松地在天气组件中引用它们,但我对如何在天气组件中使用这些选择器感到困惑,因为天气组件也是愚蠢的,不会对国家有任何参考。我只希望顶部有 1 个容器或智能组件,子组件调用或获取传递的道具。
我能看到完成这项工作的唯一方法是拥有一个WeatherContainer
看起来像这样的中间组件:
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import Weather from '../components/Weather';
import { getSummary, getDayForecast } from '../selectors/selectors';
function mapStateToProps(state, ownProps) {
return {
summary: getSummary(state, ownProps.date),
detail: getDayForecast(state, ownProps.date)
};
}
export default(connect(mapStateToProps,{}))(Weather);
我会这样称呼:
{dates.map(date => (
<WeatherContainer
key={date}
date={date}
getSummary={getSummary}
getDayForecast={getDayForecast}
/>
))}
必须创建这样的容器组件似乎是完全错误的。
我如何在哑组件中使用选择器,或者我如何将它们作为道具传递,同时记住它们也需要引用状态?