We have a render prop based class component that allows us to make a GraphQL request with a given query string and variables and uses a GitHub graphql client that is in React context to make the request. Let's refactor this to a function component that uses the hooks useReducer, useContext, and useEffect.

Class Based Component:

import {Component} from 'react'
import PropTypes from 'prop-types'
import isEqual from 'lodash/isEqual'
import * as GitHub from '../../../github-client' class Query extends Component {
static propTypes = {
query: PropTypes.string.isRequired,
variables: PropTypes.object,
children: PropTypes.func.isRequired,
normalize: PropTypes.func,
}
static defaultProps = {
normalize: data => data,
}
static contextType = GitHub.Context state = {loaded: false, fetching: false, data: null, error: null} componentDidMount() {
this._isMounted = true
this.query()
} componentDidUpdate(prevProps) {
if (
!isEqual(this.props.query, prevProps.query) ||
!isEqual(this.props.variables, prevProps.variables)
) {
this.query()
}
} componentWillUnmount() {
this._isMounted = false
} query() {
this.setState({fetching: true})
const client = this.context
client
.request(this.props.query, this.props.variables)
.then(res =>
this.safeSetState({
data: this.props.normalize(res),
error: null,
loaded: true,
fetching: false,
}),
)
.catch(error =>
this.safeSetState({
error,
data: null,
loaded: false,
fetching: false,
}),
)
} safeSetState(...args) {
this._isMounted && this.setState(...args)
} render() {
return this.props.children(this.state)
}
} export default Query

Conver props:

 // From
static propTypes = {
query: PropTypes.string.isRequired,
variables: PropTypes.object,
children: PropTypes.func.isRequired,
normalize: PropTypes.func,
}
static defaultProps = {
normalize: data => data,
} // To: function Query ({query, variables, children, normalize = data => data}) { }

Conver Context:

// From
static contextType = GitHub.Context
...
const client = this.context // To:
import {useContext} from 'react' function Query ({query, variables, children, normalize = data => data}) {
const clinet = useContext(GitHub.Context)
}

Conver State:

I don't like to cover each state prop to 'useState' style, it is lots of DRY, instead, using useReducer is a better & clean apporach.

// From
state = {loaded: false, fetching: false, data: null, error: null} //To:
import {useContext, useReducer} from 'react'
...
const [state, setState] = useReducer(
(state, newState) => ({...state, ...newState}),
defaultState)

Conver side effect:

// From:
componentDidMount() {
this._isMounted = true
this.query()
} componentDidUpdate(prevProps) {
if (
!isEqual(this.props.query, prevProps.query) ||
!isEqual(this.props.variables, prevProps.variables)
) {
this.query()
}
} componentWillUnmount() {
this._isMounted = false
} query() {
this.setState({fetching: true})
const client = this.context
client
.request(this.props.query, this.props.variables)
.then(res =>
this.safeSetState({
data: this.props.normalize(res),
error: null,
loaded: true,
fetching: false,
}),
)
.catch(error =>
this.safeSetState({
error,
data: null,
loaded: false,
fetching: false,
}),
)
} // To: useEffect(() => {
setState({fetching: true})
client
.request(query, variables)
.then(res =>
setState({
data: normalize(res),
error: null,
loaded: true,
fetching: false,
}),
)
.catch(error =>
setState({
error,
data: null,
loaded: false,
fetching: false,
}),
)
}, [query, variables]) // trigger the effects when 'query' or 'variables' changes

Conver render:

// From:
render() {
return this.props.children(this.state)
} // To:
function Query({children ... }) { ...
return children(state);
}

-----

Full Code:

import {useContext, useReducer, useEffect} from 'react'
import PropTypes from 'prop-types'
import isEqual from 'lodash/isEqual'
import * as GitHub from '../../../github-client' function Query ({query, variables, children, normalize = data => data}) {
const client = useContext(GitHub.Context)
const defaultState = {loaded: false, fetching: false, data: null, error: null}
const [state, setState] = useReducer(
(state, newState) => ({...state, ...newState}),
defaultState)
useEffect(() => {
setState({fetching: true})
client
.request(query, variables)
.then(res =>
setState({
data: normalize(res),
error: null,
loaded: true,
fetching: false,
}),
)
.catch(error =>
setState({
error,
data: null,
loaded: false,
fetching: false,
}),
)
}, [query, variables]) // trigger the effects when 'query' or 'variables' changes
return children(state)
} export default Query

[React] Refactor a Class Component with React hooks to a Function的更多相关文章

  1. [React] Refactor componentWillReceiveProps() to getDerivedStateFromProps() in React 16.3

    The componentWillReceiveProps() method is being deprecated in future version of React (17). Many of ...

  2. [React] Refactor a Stateful List Component to a Functional Component with React PowerPlug

    In this lesson we'll look at React PowerPlug's <List /> component by refactoring a normal clas ...

  3. [React Native] Create a component using ScrollView

    To show a list of unchanging data in React Native you can use the scroll view component. In this les ...

  4. React.createClass和extends Component的区别

    React.createClass和extends Component的区别主要在于: 语法区别 propType 和 getDefaultProps 状态的区别 this区别 Mixins 语法区别 ...

  5. React.Component 与 React.PureComponent(React之性能优化)

    前言 先说说 shouldComponentUpdate 提起React.PureComponent,我们还要从一个生命周期函数 shouldComponentUpdate 说起,从函数名字我们就能看 ...

  6. React Native 中的component 的生命周期

    React Native中的component跟Android中的activity,fragment等一样,存在生命周期,下面先给出component的生命周期图 getDefaultProps ob ...

  7. [React Router] Prevent Navigation with the React Router Prompt Component

    In this lesson we'll show how to setup the Prompt component from React Router. We'll prompt with a s ...

  8. React 的 PureComponent Vs Component

    一.它们几乎完全相同,但是PureComponent通过prop和state的浅比较来实现shouldComponentUpdate,某些情况下可以用PureComponent提升性能 1.所谓浅比较 ...

  9. how to design a search component in react

    how to design a search component in react react 如何使用 React 设计并实现一个搜索组件 实时刷新 节流防抖 扩展性,封装,高内聚,低耦合 响应式 ...

随机推荐

  1. express中间件的理解

    参考 :https://blog.csdn.net/huang100qi/article/details/80220012 Express中间件分为三种内置中间件.自定义中间件.第三方中间件 可以与n ...

  2. Python协程(下)

    停止子线程 如果一切正常,那么上面的例子很完美.可是,需要停止程序,直接ctrl+c,会抛出KeyboardInterrupt错误,我们修改一下主循环: try: while True: task = ...

  3. 看雪论坛 破解exe 看雪CTF2017第一题分析-『CrackMe』-看雪安全论坛

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 逆向 黑客 破解 学习 论坛 『CrackMe』 http://bbs.pediy.co ...

  4. 【BZOJ1098】[POI2007]办公楼biu

    题目一开始看以为和强联通分量有关,后来发现是无向边,其实就是求原图的补图的联通块个数和大小.学习了黄学长的代码,利用链表来优化,其实就是枚举每一个人,然后把和他不相连的人都删去放进同一个联通块里,利用 ...

  5. bzoj1093 [ZJOI2007]最大半联通子图 缩点 + 拓扑序

    最大半联通子图对应缩点后的$DAG$上的最长链 复杂度$O(n + m)$ #include <cstdio> #include <cstring> #include < ...

  6. poj 2001 trie

    第一道trie 还需要写题来建立自己的代码习惯. #include <cstdio> #include <vector> #include <algorithm> ...

  7. 【R笔记】R语言函数总结

    R语言与数据挖掘:公式:数据:方法 R语言特征 对大小写敏感 通常,数字,字母,. 和 _都是允许的(在一些国家还包括重音字母).不过,一个命名必须以 . 或者字母开头,并且如果以 . 开头,第二个字 ...

  8. SCOJ 4427: Miss Zhao's Graph dp

    4427: Miss Zhao's Graph 题目连接: http://acm.scu.edu.cn/soj/problem.action?id=4427 Description Mr Jiang ...

  9. Shell基础学习(二) Shell变量

    1.数据类型: 字符串 数组 2.变量的命名规范: 只能以a-z或A-Z开头 中间不能有空格,可以使用_ 不能使用标点符号 不能使用shell的关键字 3.变量类型: 环境变量 局部变量 shell变 ...

  10. 开源数据库 H2, HSQLDB, DERBY, PostgreSQL, MySQL区别/对比图表( 附加翻译) h2数据库

    开源数据库 H2, HSQLDB, DERBY, PostgreSQL, MySQL区别/对比图表 浪天涯博主翻译: referential integrity 参考完整性transactions 事 ...