智能/哑组件使用选择说我有一个最顶层的智能组件调用预测,看起来像这样:在终极版
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') }))
);
我没有通过这些选择下来的道具,我可以很容易地只是参考他们在天气组件,但我很困惑,我怎么会用在这些选择Weather组件作为Weather组件也是愚蠢的,并且不会有任何状态的引用。我只想要一个容器或智能组件在顶层,子组件调用或获取道具传递。
我可以看到使这项工作的唯一方法是有一个intermediatary 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}
/>
))}
这似乎必须创建像这样的容器组件是完全错误的。
我怎样才能使哑元件使用选择的或如何传递下来的道具记住霸菱,他们也需要参照状态?
你的选择器返回的是不可变的对象,这是过度杀伤。与普通物体相比,它的性能也更差,也更难使用。把React-Redux上下文中的'props'想象成一个临时变量。这是不变的,但没有必要执行或管理。 – DDS