组件式开发

#积累/react

组件再分离

组件分离为颗粒度更细的组件,是纯粹的、木偶式的 ,可以在真实业务中进行任意组合。

逻辑再抽象

组件中的相同交互逻辑和业务逻辑也应该进行抽象。

  1. 接口数据请求的抽象
    数据请求的逻辑提升到高阶组件,把数据作为props属性赋予子组件。
    可以结合context

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    const asyncSelectDecorator = WrappedComponent => {
    class AsyncSelectDecorator extends Component {
    componentDidMount () {
    const {url, params} = this.props;
    fetch (url, {params}).then (data => {
    this.setState ({
    data,
    });
    });
    }
    render () {
    return <WrappedComponent {...this.props} data={this.state.data} />;
    }
    }
    return AsyncSelectDecorator;
    };
  2. 组件交互逻辑和状态抽象
    将SearchInput 与 List 的交互的状态data和keyword,以及改变状态的方法抽取出来

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    // 完成 SearchInput 与 List 的交互
    const searchDecorator = WrappedComponent => {
    class SearchDecorator extends Component {
    constructor (props) {
    super (props);
    this.handleSearch = this.handleSearch.bind (this);
    }
    handleSearch (keyword) {
    this.setState ({
    data: this.props.data,
    keyword,
    });
    this.props.onSearch (keyword);
    }
    render () {
    const {data, keyword} = this.state;
    return (
    <WrappedComponent
    {...this.props}
    data={data}
    keyword={keyword}
    onSearch={this.handleSearch}
    />
    );
    }
    }
    return SearchDecorator;
    };
  3. 组件式开发的最终效果

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    const FinalSelector = compose (
    asyncSelectDecorator,
    searchDecorator,
    selectedItemDecorator
    ) (Selector);
    class SearchSelect extends Component {
    render () {
    return (
    <FinalSelector {...this.props}>
    <SelectInput />
    <SearchInput />
    <List />
    </FinalSelector>
    );
    }
    }