我有一個容器組件,它將一組對象傳遞給一個表示組件輸出。反應:將簡單的邏輯放在Container或Presentational組件中?
在演示組件中,我需要顯示符合特定條件的這些對象的數量。最好的做法是在容器組件中執行計數並將其傳遞給演示組件,或者可以在演示組件中進行計數。
即:
export class ResultsPage extends React.Component {
constructor(props){
super(props);
}
countSexyObjects(){
const matching = this.props.allObjects.filter((obj)=>{
return obj.sexy === true;
});
return matching.length
}
render(){
return (
<PresentationalComponent allObjects={this.props.allObjects}
numberOfSexyObjects={this.countSexyObjects()} />
);
}
}
let PresentationalComponent = (props) => {
return (
<div>
There are {props.numberOfSexyObjects} sexy objects
</div>
);
};
OR
export class ResultsPage extends React.Component {
constructor(props){
super(props);
}
render(){
return (
<PresentationalComponent allObjects={this.props.allObjects} />
);
}
}
let PresentationalComponent = (props) => {
const countSexyObjects =() => {
const matching = this.props.allObjects.filter((obj)=>{
return obj.sexy === true;
});
return matching.length
};
return (
<div>
There are {countSexyObjects()} sexy objects
</div>
);
};
此鏈接可能會有所幫助 - https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.2vdpxfulp – kaushik94