reactjs - Hooks & Context & (State / Reducer) 的代码结构/模式
问题描述
我如何重构下面的代码以获得更好、更简洁的代码,并尊重最佳实践,因为我觉得当前的代码真的很混乱。
使用下面的代码,我应该从 useState 切换到 useReducer 吗?减速器是否应该在单独的文件中(例如:src/reducers/NotificationReducer.js)?
另外,我应该在哪里实现获取数据的功能?在组件/上下文/其他东西中?我觉得在上下文中获取数据是错误的,不属于这里。
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
解决方案
您已经在查看组件中要发生的很多事情。除非您切换到组件外部的状态管理,否则您无能为力。看看redux-toolkit,它将向您展示如何在功能中构建您的应用程序,例如:用户、通知和 authedUser。fetchData 也将成为异步 thunk,而“hasNewNotifications”和“isLoading”可以根据您的异步请求状态(待处理/已完成/已拒绝)设置
推荐阅读
- python - 使用 selenium 抓取 Instagram 关注者
- python - 大数据集的特征缩放
- cassandra - 选择查询冻结列表 Cassandra
- python - scipy.stats.skew nan_policy 参数
- unity3d - Android 的公共游戏可以使用 Unity Personal
- sql - T-SQL 为每个客户分配 10,000 张发票
- html - 如何让浏览器窗口和 div 之间的空隙消失?
- jmeter - Jmeter:在 Windows 中运行的测试计划在 Centos 中失败
- hive - Hive 导出到 AVRO,架构中没有列名
- java - 错误消息:java.lang.IllegalArgumentException