React中如何跨组件访问React Query更新的useState状态follower的长度
现有代码优化
你当前的写法存在冗余:不需要额外用useState存储接口返回的follower数据,useQuery本身返回的data字段就会自动存储接口响应结果,调整后的ModalFollower可以简化为:
const ModalFollower = ({profile}) => { const { data: follower = [], // 直接把接口返回的响应赋值给follower,默认空数组 isLoading: followerLoading, isFetching: followerFetching // 查询函数直接返回getFollowers的Promise即可,不需要自行在then里更新状态 } = useQuery(["invitations", profile?.id], () => getFollowers(profile?.id), { enabled: !!profile?.id // 新增:profile id不存在时不发起请求,避免报错 }); return !followerLoading ? ( follower.map((e, index) => ( <p key={index}>{e.requested_profile.Userlink}</p> )) ) : null }
其他组件访问follower长度的实现方案
根据你的组件层级和业务场景,可以从下面三种方案里选最合适的:
方案1:复用React Query缓存(最推荐,无需修改现有组件结构)
React Query会根据查询key缓存请求结果,其他组件只要使用相同的key ["invitations", profile?.id] 调用useQuery,就能直接拿到缓存的follower数据,不需要跨组件传参:
// 其他需要获取follower长度的组件 const OtherComponent = ({profile}) => { const { data: follower = [] } = useQuery(["invitations", profile?.id], { enabled: !!profile?.id, staleTime: 5 * 60 * 1000 // 可以自定义缓存有效时间,避免重复发起请求 }) // 直接获取长度即可 const followerCount = follower.length return <div>关注者数量:{followerCount}</div> }
方案2:状态提升(适合两个组件层级接近的场景)
如果ModalFollower和需要访问follower长度的组件有公共的近层级父组件,可以把useQuery的逻辑提到公共父组件中,再通过props把数据传给两个子组件:
// 公共父组件 const Parent = () => { const [profile, setProfile] = useState(/* 你的profile数据 */) const { data: follower = [], isLoading: followerLoading, } = useQuery(["invitations", profile?.id], () => getFollowers(profile?.id), { enabled: !!profile?.id }) return ( <> {/* 把数据传给ModalFollower */} <ModalFollower profile={profile} follower={follower} followerLoading={followerLoading} /> {/* 把长度传给需要的组件 */} <TargetComponent followerCount={follower.length} /> </> ) } // 改造后的ModalFollower,不需要自己发起请求和维护状态 const ModalFollower = ({profile, follower, followerLoading}) => { return !followerLoading ? ( follower.map((e, index) => ( <p key={index}>{e.requested_profile.Userlink}</p> )) ) : null }
方案3:Context全局共享(适合多组件、深层级需要访问数据的场景)
如果需要用到follower数据的组件层级很深,逐层传props成本太高,可以创建Context全局共享数据:
import { createContext, useContext } from 'react' // 1. 创建Context const FollowerContext = createContext({ follower: [] }) // 2. 用Provider包裹需要用到数据的所有业务组件 export const FollowerProvider = ({ children, profile }) => { const { data: follower = [], isLoading: followerLoading, } = useQuery(["invitations", profile?.id], () => getFollowers(profile?.id), { enabled: !!profile?.id }) return ( <FollowerContext.Provider value={{ follower, followerLoading }}> {children} </FollowerContext.Provider> ) } // 3. 任何组件都可以通过useContext直接获取follower数据 const AnyComponent = () => { const { follower } = useContext(FollowerContext) return <div>关注者数量:{follower.length}</div> }
内容的提问来源于stack exchange,提问作者Pratham Sampat
相关产品推荐
相关产品推荐

