代码复用逻辑:Vue vs react

649 阅读1分钟

vue中mixin可以复用代码逻辑,存在缺点:1.代码来源不明 2.难以理解。以一个音乐播放器为例,播放列表是一段共用逻辑,可以抽离出来。搜索也是一段共用逻辑,也可以单独抽离出来。在一个搜索页面中会引用这两个mixin。两个mixin还不算太糟糕要是有多个呢

export const playlistMixin = {
  computed: {
    ...mapGetters([
      'playlist'
    ])
  },
  mounted() {
    this.handlePlaylist(this.playlist)
  },
  activated() {
    this.handlePlaylist(this.playlist)
  },
  watch: {
    playlist(newVal) {
      this.handlePlaylist(newVal)
    }
  },
  methods: {
    handlePlaylist() {
      throw new Error('component must implement handlePlaylist method')
    }
  }
}

export const searchMixin = {
  data() {
    return {
      query: '',
      refreshDelay: 120
    }
  },
  computed: {
    ...mapGetters([
      'searchHistory'
    ])
  },
  methods: {
    onQueryChange(query) {
      this.query = query
    },
    blurInput() {
      this.$refs.searchBox.blur()
    },
    addQuery(query) {
      this.$refs.searchBox.setQuery(query)
    },
    saveSearch() {
      this.saveSearchHistory(this.query)
    },
    ...mapActions([
      'saveSearchHistory',
      'deleteSearchHistory'
    ])
  }
}

react中的高阶组件也可以复用,但代码也不易理解。下面示例为请求一个网址,通过自定义url拿到数据后返回后返回,通过判断数据状态显示哪些节点,可以看到除了返回所需节点之外还增加了一些新的节点

import React from 'react'import axios from 'axios'interface ILoaderState {  data: any,  isLoading: boolean}interface ILoaderProps {  data: any,}const withLoader = <P extends ILoaderState>(WrappedComponent: React.ComponentType<P>, url: string) => {  return class LoaderComponent extends React.Component<Partial<ILoaderProps>, ILoaderState> {    constructor(props: any) {      super(props)      this.state = {        data: null,        isLoading: false      }    }    componentDidMount() {      this.setState({        isLoading: true,      })      axios.get(url).then(result => {        this.setState({          data: result.data,          isLoading: false        })      })    }    render() {      const { data, isLoading } = this.state      return (        <>          { (isLoading || !data) ? <p>data is loading</p> :            <WrappedComponent {...this.props as P} data={data} />          }        </>      )    }  }}export default withLoader

3.react hook