首页 > 解决方案 > Hooks & Context & (State / Reducer) 的代码结构/模式

问题描述

src/context/NotificationsContext.js - (简化)

export const NotificationsContext = createContext()

export const NotificationsProvider = (props) => {
  const [totalPages, setTotalPages] = useState(null)
  const [currentPage, setCurrentPage] = useState(1)
  const [user, setUser] = useContext(UserContext)
  const [hasNewNotifications, setHasNewNotifications] = useState(false)
  const [notifications, setNotifications] = useState([])
  const [isLoading, setIsLoading] = useState(true)

  async function fetchData() {
    setIsLoading(true)
    ...
    // fetching the data
    ..
    setHasNewNotifications(...)
    setNotifications(...)
    setTotalPages(...)
    setIsLoading(false)
  }

  async function readNotification() {
    // sending the request to read the notification
    setNotifications(...)
  }


  return (
    <NotificationsContext.Provider
      value={[
        notifications,
        setNotifications,
        isLoading,
        setIsLoading,
        hasNewNotifications,
        setHasNewNotifications,
        fetchData,
        readNotification,
      ]}
    >
      {props.children}
    </NotificationsContext.Provider>
  )
}

src/components/Notifications.js - (简化)

const Notification = ({index}) => {
  const [
    notifications,
    setNotifications,
    loading,
    setIsLoading,
    hasNewNotifications,
    setHasNewNotifications,
    fetchData,
    readNotification,
  ] = useContext(NotificationsContext)


  return (
    <div>
        notifications.map((notif, index) => {
            return <Notification index={index}/> //the component Notification holds the actual representation for a notification
        })
    </div>
  )
}

export default Notification

src/components/Notification.js - (简化)

const Notification = ({index}) => {
  const [
    notifications,
    setNotifications,
    loading,
    setIsLoading,
    hasNewNotifications,
    setHasNewNotifications,
    fetchData,
    readNotification,
  ] = useContext(NotificationsContext)


  return (
    // very simplified compenent to understand better
    <div></div>
        <button onClick={() => readNotification(...)}
        <div>{notifications[index].message</div>
    </div>
  )
}

export default Notification

标签: reactjsreact-hooksreact-state

解决方案


您已经在查看组件中要发生的很多事情。除非您切换到组件外部的状态管理,否则您无能为力。看看redux-toolkit,它将向您展示如何在功能中构建您的应用程序,例如:用户、通知和 authedUser。fetchData 也将成为异步 thunk,而“hasNewNotifications”和“isLoading”可以根据您的异步请求状态(待处理/已完成/已拒绝)设置


推荐阅读