javascript - 由于上下文中未使用的属性,组件重新渲染
问题描述
我有一个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>
), [])
}
它也有效,它更简洁,但我不确定这是否是一个好习惯。
我的两种方法中的任何一种都正确吗?如果没有,你有什么建议?
解决方案
我想我找到了最好的方法,这要归功于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)
并且我没有重新渲染。
推荐阅读
- reactjs - 应用样式会扭曲 React Callout 组件
- javascript - 如何创建一个保持不变且在 Javascript 中不变的随机数?
- r - 根据多个其他列更改各个列 - R
- flutter - Flutter 构建失败并出现致命错误:找不到“Flutter/Flutter.h”文件
- hive - 如何将所有映射器加载到 HIVE 表中?
- python - 从调用 .txt 文件中删除 /n python
- c - 使用 Raspberry Pi 和 BCM2835 库写入 LCD 屏幕时出现问题
- python - 狮身人面像中的“没有名为'气流'的模块”
- sql - 如何用表中的值进行替换
- rust - 生命周期和实现克隆的问题