You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React 17 组件formatTags函数执行两次故障原因咨询

原因分析

  • 第一次执行:组件首次渲染
    组件挂载时第一次渲染,此时fetchTags发起的接口请求尚未返回结果,Redux中存储的tags.items还是初始值(空数组/undefined),渲染逻辑调用formatTags处理初始状态的标签数据,返回null传给Filter组件。
  • 第二次执行:Redux状态更新触发重渲染
    接口请求拿到标签数据后,会更新Redux中tags.items的状态值,你的组件通过mapStateToProps订阅了tags状态,状态变更会触发组件重新渲染,此时会再次调用formatTags处理最新的标签数据,返回符合react-select格式要求的选项数组。

可选优化方案

如果要避免不必要的重复计算,可以用useMemo缓存标签格式化的结果,只有tags发生变化时才重新计算:

import { Fragment, useEffect, useMemo } from 'react'
// 其余引入保持不变

export const DocumentsPresentational = props => {
    const { fetchTags, tags } = props

    useEffect(() => {
        fetchTags()
    }, [fetchTags])

    // 缓存格式化结果,仅tags变化时重新计算
    const tagOptions = useMemo(() => {
        if (!tags || tags.length === 0) return null
        return tags.map(item => ({
            label: item.key,
            value: item.key
        }))
    }, [tags])

    return (
        <Fragment>
            {/* 其余结构保持不变 */}
            <Filter
                options={tagOptions}
            />
            {/* 其余结构保持不变 */}
        </Fragment>
    )
}
// 后续mapStateToProps、mapDispatchToProps等逻辑保持不变

内容的提问来源于stack exchange,提问作者sineverba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 10:54:02