React中如何处理修改父组件state的重复函数代码
React 通知逻辑复用的规范实现方案
针对你提到的跨页面通知逻辑重复的问题,React官方提供了多种成熟的逻辑复用方案,以下是优先级从高到低的实现方式:
1. 自定义Hook(推荐,适配函数组件)
将通知状态、增删逻辑全部封装到独立的自定义Hook中,所有需要用到通知的页面直接引入调用即可,完全避免重复代码:
import { useState } from 'react' // 独立封装的通知逻辑Hook,可单独放到utils/hooks目录下复用 function useNotifications(initialNotifications = []) { const [notifications, setNotifications] = useState(initialNotifications) // 按索引删除通知 const removeNotifAt = (index) => { setNotifications(prevState => { const copy = [...prevState] copy.splice(index, 1) return copy }) } // 按ID删除通知 const removeNotifyBy = (id) => { setNotifications(prevState => { const copy = [...prevState] const targetIndex = copy.findIndex(notif => notif.id === id) if (targetIndex > -1) copy.splice(targetIndex, 1) return copy }) } // 可扩展添加通知、清空通知等方法 const addNotification = (newNotif) => { setNotifications(prevState => [...prevState, newNotif]) } return { notifications, removeNotifAt, removeNotifyBy, addNotification } }
页面组件使用方式:
import Notifications from './Notifications' import useNotifications from 'hooks/useNotifications' function Page() { // 一行代码获取所有通知相关状态和方法 const { notifications, removeNotifAt, removeNotifyBy } = useNotifications() return ( <div className="page"> {/* 页面其他内容 */} {notifications.length > 0 && ( <Notifications notifications={notifications} removeNotifAt={removeNotifAt} removeNotifyBy={removeNotifyBy} /> )} </div> ) }
2. 高阶组件(HOC,适配类组件)
如果你还在使用类组件开发,可以用高阶组件的方式将通知逻辑注入到页面组件的props中:
import React from 'react' function withNotifications(WrappedComponent) { return class extends React.Component { state = { notifications: [] } removeNotifAt = (index) => { this.setState(prevState => { const copy = [...prevState.notifications] copy.splice(index, 1) return { notifications: copy } }) } removeNotifyBy = (id) => { this.setState(prevState => { const copy = [...prevState.notifications] const targetIndex = copy.findIndex(notif => notif.id === id) if (targetIndex > -1) copy.splice(targetIndex, 1) return { notifications: copy } }) } addNotification = (newNotif) => { this.setState(prevState => ({ notifications: [...prevState.notifications, newNotif] })) } render() { return ( <WrappedComponent {...this.props} notifications={this.state.notifications} removeNotifAt={this.removeNotifAt} removeNotifyBy={this.removeNotifyBy} addNotification={this.addNotification} /> ) } } }
类组件使用方式:
class Page extends React.Component { render() { // 直接从props获取通知相关属性和方法 const { notifications, removeNotifAt, removeNotifyBy } = this.props return ( <div className="page"> {/* 页面其他内容 */} {notifications.length > 0 && ( <Notifications notifications={notifications} removeNotifAt={removeNotifAt} removeNotifyBy={removeNotifyBy} /> )} </div> ) } } // 导出时用高阶组件包裹即可 export default withNotifications(Page)
3. Context全局状态(适配全局通知场景)
如果你的通知是全局统一展示的(比如所有页面的通知都挂在顶层Layout的右上角),可以用React Context封装全局通知状态,所有组件都可以直接调用添加/删除通知的方法,不需要每个页面单独引入逻辑。
以上三种都是React官方推荐的逻辑复用方案,完全符合React设计规范,不需要在每个父组件重复编写相同的状态修改逻辑。
内容的提问来源于stack exchange,提问作者Sebastian Nielsen
相关产品推荐
相关产品推荐

