In the class version of this component, we had a method called safeSetState which would check whether the component was still mounted before trying to call setState. This is because our graphql client library is unable to cancel in-flight requests. Let's make that same kind of thing work by tracking the mounted state of our component using the useRef and useEffect hooks.

We want a "lock", which should run once when component inited, after component unmounted, it should be reseted.

We can use 'useRef' to build a container to hold our lock:

  const mountedRef = useRef(false);

Then we can use useEffect:

  useEffect(() => {
mountedRef.current = true
return () => (mountedRef.current = false)
}, [])

The reason to use '[]' as second arguement, is because we don't want useEffect be triggered second times, we only want to run once, therefore, we use empty array, it won't trigger scecond time.

Then we can create a safe setSetate function:

  const [state, setState] = useReducer(
(state, newState) => ({...state, ...newState}),
{
loaded: false,
fetching: false,
data: null,
error: null,
},
) const setSafeState = (...args) => mountedRef.current && setState(...args);

----

Full code:

import {useContext, useReducer, useEffect, useRef} from 'react'
import PropTypes from 'prop-types'
import isEqual from 'lodash/isEqual'
import * as GitHub from '../../../github-client' function useSetState(initialState) {
return useReducer(
(state, newState) => ({...state, ...newState}),
initialState,
)
} function useSafeSetState(initialState) {
const [state, setState] = useSetState(initialState) const mountedRef = useRef(false)
useEffect(() => {
mountedRef.current = true
return () => (mountedRef.current = false)
}, [])
const safeSetState = (...args) => mountedRef.current && setState(...args) return [state, safeSetState]
} function Query({query, variables, normalize = data => data, children}) {
const client = useContext(GitHub.Context)
const [state, setState] = useSafeSetState({
loaded: false,
fetching: false,
data: null,
error: null,
}) useEffect(() => {
if (isEqual(previousInputs.current, [query, variables])) {
return
}
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,
}),
)
}) const previousInputs = useRef()
useEffect(() => {
previousInputs.current = [query, variables]
}) return children(state)
} Query.propTypes = {
query: PropTypes.string.isRequired,
variables: PropTypes.object,
children: PropTypes.func.isRequired,
normalize: PropTypes.func,
} export default Query

[React] Safely setState on a Mounted React Component through the useEffect Hook的更多相关文章

  1. React的setState分析

    前端框架层出不穷,不过万变不离其宗,就是从MVC过渡到MVVM.从数据映射到DOM,angular中用的是watcher对象,vue是观察者模式,react就是state了. React通过管理状态实 ...

  2. React的setState执行机制

    1. setState基本特点 1. setState是同步执行的 setState是同步执行的,但是state并不一定会同步更新 2. setState在React生命周期和合成事件中批量覆盖执行 ...

  3. React中setState同步更新策略

    setState 同步更新 我们在上文中提及,为了提高性能React将setState设置为批次更新,即是异步操作函数,并不能以顺序控制流的方式设置某些事件,我们也不能依赖于this.state来计算 ...

  4. 初学React,setState后获取到的thisstate没变,还是初始state?

    问题:(javascript)初学React,setState后获取到的thisstate没变,还是初始state?描述: getInitialState(){ return {data:[]}; } ...

  5. React中setState学习总结

    react中setState方法到底是异步还是同步,其实这个是分在什么条件下是异步或者同步. 1.先来回顾一下react组件中改变state的几种方式: import React, { Compone ...

  6. React的setState学习及应用

    React的setState学习及应用 一:作用: setState() 将对组件 state 的更改排入队列,并通知 React 需要使用更新后的 state 重新渲染此组件及其子组件.这是用于更新 ...

  7. React 的setState 理解

    我们都知道在React中,setState() 方法是用来改变组件状态的,在项目中也一直用,也没有出现什么问题(使用方法太简单了),但今天看了一篇文章,提到了setState 使用时的两个注意点,加深 ...

  8. react中setState用法

    setState()更新状态的2种写法 setState(updater, [callback]), updater为返回stateChange对象的函数: (state, props) => ...

  9. React中setState 什么时候是同步的,什么时候是异步的?

    class Example extends React.Component { constructor() { super(); this.state = { val: 0 }; } componen ...

随机推荐

  1. scrapy实现多级页面的抓取时使用meta传递item数据的问题(转)

    name = 'doubanzufang'start_urls = ['https://www.douban.com/group/tianhezufang/discussion?start=50'] ...

  2. BZOJ1017 魔兽地图DotR (树上背包)

    一道背包的神题,用到了树上dp和背包dp,这个题的特殊性在于儿子对于父亲节点是有影响的,所以用f[i][j][k]表示第i号装备,其中用j个来合成上层装备,花费k元所能获得最大的力量值. 然后对于每一 ...

  3. Activity研究

    ActivityManagerService 业务的整个逻辑关系被各种复杂的数据结构包裹着,因此对ActivityManagerService 的分析主要就是对各种数据结构的分析,明白了这些数据结构, ...

  4. Java并发(十二):CAS Unsafe Atomic

    一.Unsafe Java无法直接访问底层操作系统,而是通过本地(native)方法来访问.不过尽管如此,JVM还是开了一个后门,JDK中有一个类Unsafe,它提供了硬件级别的原子操作. 这个类尽管 ...

  5. hdu 3081

    二分答案,网络流是否满流判断合法性. #include <cstdio> #include <cstring> #include <queue> #include ...

  6. ZOJ 1015 弦图判定

    一些定义: 弦图是一种特殊图:它的所有极小环都只有3个顶点. 单纯点:该顶点与其邻接点在原图中的导出子图是一个完全图. 图G的完美消去序列:一个顶点序列a1a2a3...an,使得对于每个元素ai,a ...

  7. hihocoder 1519 : 逃离迷宫II

    题目链接 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi被坏女巫抓进里一间有N x M个格子组成的矩阵迷宫. 有些格子是小Hi可以经过的,我们用'.'表示:有些格 ...

  8. IOS发送Email的两种方法

    IOS系统框架提供的两种发送Email的方法:openURL 和 MFMailComposeViewController.借助这两个方法,我们可以轻松的在应用里加入如用户反馈这类需要发送邮件的功能. ...

  9. Buck converter uses low-side PWM IC

    The most common switching-power topology is a buck converter, which efficiently transforms high volt ...

  10. 几个未公开的 DBCC 命令

    http://blog.csdn.net/CathySun118/article/category/538610 https://ask.hellobi.com/blog/lyhabc/1612 1. ...