智能/啞組件使用選擇說我有一個最頂層的智能組件調用預測,看起來像這樣:在終極版
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