美文网首页
组件和容器

组件和容器

作者: 张义飞 | 来源:发表于2018-05-04 13:04 被阅读0次

组件和组件容器

我们可以通过一个例子来说明组件和组件容器的作用,比如下面的始终的例子。

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = { time: this.props.time };
    this._update = this._updateTime.bind(this);
  }
  render() {
    const time = this._formatTime(this.state.time);
    return (
      <h1>
        { time.hours } : { time.minutes } : { time.seconds }
      </h1>
    );
  }
  componentDidMount() {
    this._interval = setInterval(this._update, 1000);
  }
  componentWillUnmount() {
    clearInterval(this._interval);
  }
  _formatTime(time) {
    var [ hours, minutes, seconds ] = [
      time.getHours(),
      time.getMinutes(),
      time.getSeconds()
    ].map(num => num < 10 ? '0' + num : num);

    return { hours, minutes, seconds };
  }
  _updateTime() {
    this.setState({
      time: new Date(this.state.time.getTime() + 1000)
    });
  }
};

ReactDOM.render(<Clock time={ new Date() }/>, ...);

我们可以看到click这个组件担任的责任有点多,view层以及数据处理逻辑等都是在这里面进行处理的,其中数据和view都不能被其他组件共享。

提取组件

组件应该是由纯函数构造而成的,它内部不应该有状态。

// Clock/Clock.jsx
export default function Clock(props) {
  var [ hours, minutes, seconds ] = [
    props.hours,
    props.minutes,
    props.seconds
  ].map(num => num < 10 ? '0' + num : num);

  return <h1>{ hours } : { minutes } : { seconds }</h1>;
};

提取容器

容器应该是各个组件进行组合和数据处理的地方。

// Clock/index.js
import Clock from './Clock.jsx'; // <-- that's the presentational component

export default class ClockContainer extends React.Component {
  constructor(props) {
    super(props);
    this.state = { time: props.time };
    this._update = this._updateTime.bind(this);
  }
  render() {
    return <Clock { ...this._extract(this.state.time) }/>;
  }
  componentDidMount() {
    this._interval = setInterval(this._update, 1000);
  }
  componentWillUnmount() {
    clearInterval(this._interval);
  }
  _extract(time) {
    return {
      hours: time.getHours(),
      minutes: time.getMinutes(),
      seconds: time.getSeconds()
    };
  }
  _updateTime() {
    this.setState({
      time: new Date(this.state.time.getTime() + 1000)
    });
  }
};

优点

职责的划分更加明显:容器不需要了解图形的绘制,组件不需要了解数据的处理。
重用性更高:由于组件只是用来显示数据没有太多的业务逻辑,就能很好的被拿来重用

相关文章

网友评论

      本文标题:组件和容器

      本文链接:https://www.haomeiwen.com/subject/sfjdrftx.html