首页 > 解决方案 > 由于上下文中未使用的属性,组件重新渲染

问题描述

我有一个AsyncContext允许我开始/停止任何类型的异步计算。在幕后,它管理着一个全局加载器和一个小吃店。

export type Context = {
  loading: boolean
  start: () => void
  stop: (message?: string) => void
}

const defaultContext: Context = {
  loading: false,
  start: noop,
  stop: noop,
}

export const AsyncContext = createContext(defaultContext)

这里有一个消费者:

const MyChild: FC = () => {
  const {start, stop} = useContext(AsyncContext)

  async function fetchUser() {
    try {
      start()
      const res = await axios.get('/user')
      console.log(res.data)
      stop()
    } catch (e) {
      stop('Error: ' + e.message)
    }
  }

  return (
    <button onClick={fetchData}>
      Fetch data
    </button>
  )
}

如您所见,MyChild不关心loading. 但它包含在上下文中,因此组件重新渲染了 2 次。

为了防止这种情况,我的第一次尝试是将我的组件分成两部分,并使用memo

type Props = {
  start: AsyncContext['start']
  stop: AsyncContext['stop']
}

const MyChild: FC = () => {
  const {start, stop} = useContext(AsyncContext)
  return <MyChildMemo start={start} stop={stop} />
}

const MyChildMemo: FC<Props> = memo(props => {
  const {start, stop} = props

  async function fetchUser() {
    try {
      start()
      const res = await axios.get('/user')
      console.log(res.data)
      stop()
    } catch (e) {
      stop('Error: ' + e.message)
    }
  }

  return (
    <button onClick={fetchData}>
      Fetch data
    </button>
  )
})

它有效,但我不想拆分所有使用AsyncContext.

第二种尝试是useMemo直接在 JSX 上使用:

const MyChild: FC = () => {
  const {start, stop} = useContext(AsyncContext)

  async function fetchUser() {
    try {
      start()
      const res = await axios.get('/user')
      console.log(res.data)
      stop()
    } catch (e) {
      stop('Error: ' + e.message)
    }
  }

  return useMemo(() => (
    <button onClick={fetchData}>
      Fetch data
    </button>
  ), [])
}

它也有效,它更简洁,但我不确定这是否是一个好习惯。

我的两种方法中的任何一种都正确吗?如果没有,你有什么建议?

标签: javascriptreactjstypescriptreact-hooksrerender

解决方案


我想我找到了最好的方法,这要归功于https://kentcdodds.com/blog/how-to-use-react-context-effectively:将上下文分隔在两个上下文中。一份用于州,一份用于调度:

type StateContext = boolean
type DispatchContext = {
  start: () => void
  stop: (message?: string | void) => void
}

export const AsyncStateContext = createContext(false)
export const AsyncDispatchContext = createContext({start: noop, stop: noop})

如果消费者不需要状态,我只是添加const {start, stop} = useContext(AsyncDispatchContext)并且我没有重新渲染。


推荐阅读