React:在Container或Presentational组件中放入简单的逻辑?

问题描述 投票:2回答:2

我有一个容器组件,它将一组对象传递给一个表示组件进行输出。

在表示组件中,我需要显示满足特定条件的许多这些对象的计数。最佳做法是在容器组件中执行计数并将其传递给表示组件,还是可以在表示组件中进行此计数。

即:

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>
  );
};
reactjs jsx
2个回答
1
投票

理想情况下,国家被认为是反应中的邪恶。我理解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组件。


1
投票

我会使用第一种格式,原因如下:

  • 智能组件应该更好地了解“SexyObject”是什么。如果它是对象中的一个字段,那很简单,可以用任何一种方式进行论证。如果它依赖于Web服务或一些更复杂的逻辑来确定它是否性感,那么您在表示层中永远不会想要它。简单有一种变得复杂的方式,所以我最初会使用支持复杂性的结构。
  • 使用智能组件中的逻辑,测试代码会更简单。您可以填充组件,然后检查固定数据集中的输出变量。
  • 如果组件可以更改“SexyObject”的条件,那么如果将选择逻辑分开,则可以保留重用表示组件的功能。

只需我0.02美元

© www.soinside.com 2019 - 2024. All rights reserved.