我有一个容器组件,它将一组对象传递给一个表示组件进行输出。
在表示组件中,我需要显示满足特定条件的许多这些对象的计数。最佳做法是在容器组件中执行计数并将其传递给表示组件,还是可以在表示组件中进行此计数。
即:
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>
);
};
要么
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>
);
};
理想情况下,国家被认为是反应中的邪恶。我理解React建立在状态的概念之上,但更少的状态是更优选的,这意味着尝试用大多数本质上纯粹的函数来构造代码。
你的第一个例子中的恕我直言更正确。 ResultsPage
是你的容器组件(智能组件),而另一个是愚蠢的。 Dumb组件不管理状态,只关注UI的外观。您可以将所有html,bootstrap逻辑放在那里。
这种模式好的原因是因为我们现在想要从XHR调用中获取匹配条件,在第二种情况下你的代码将是
export class ResultsPage extends React.Component {
constructor(props){
super(props);
}
getSexyMatcher() {
/* make ajax call here */
return results;
}
render(){
return (
<PresentationalComponent allObjects={this.props.allObjects} sexyMatcher={getSexyMatcher()}/>
);
}
}
let PresentationalComponent = (props) => {
const countSexyObjects = () => {
const matching = this.props.allObjects.filter((obj)=>{
return obj.sexy.match(props.sexyMatcher)
// return obj.sexy === true;
});
return matching.length
};
return (
<div>
There are {countSexyObjects()} sexy objects
</div>
);
};
请注意您是如何为同一业务逻辑更改两个组件的?更糟糕的是,如果其他人在代码库中的其他地方使用了PresentationalComponent
呢?在第一种情况下,事情要简单得多。只需在智能组件中添加ajax函数,并将结果传递给UI组件。
我会使用第一种格式,原因如下:
只需我0.02美元