javascript - 将现有上下文传递给我的 setContext 反应钩子(JS 问题)
问题描述
我当前的上下文以及设置更新上下文的方法如下所示:
export const AppContextProvider = ({ children }) => {
const [currentAppContext, setCurrentAppContext] = useState(initApp)
const setAppContext = values => {
setCurrentAppContext(values)
}
return <AppContext.Provider value={{ appContext: currentAppContext, setAppContext }}>{children}</AppContext.Provider>
}
我在一个组件中设置了新的上下文,如下所示:
export default function Settings() {
const { appContext, setAppContext } = useContext(AppContext)
const func = ({ accountId }) => {
setAppContext({
...appContext,
accountId: accountId,
})
},
})
return <></>
}
但我更愿意 setAppContext((currentContext) => ({...currentContext, accountId: accountId}))
像我们在useReducer
钩子上做的那样做useReducer(state => state.item)
。这可能吗,如果可以,我该怎么写?
解决方案
从返回的 set 函数useState()
允许您像这样传递一个函数,所以实际上不需要更改我的代码来允许这种情况发生,它已经工作了!
推荐阅读
- sql-server - 如何在 rdlc 和 vb,net 中的报告上显示参数值
- android-studio - 右键单击 res 文件夹时找不到“在资源管理器中显示”
- android - 在数据库中获取空白条目
- c# - 异常没有被 catch 捕获
- eclipse - 如何在 Eclipse 中安装插件开发的源代码?
- sql - 如何编写 SQL 查询以获得以下场景输出
- angular - 在 HTTP 响应后调用时,角度数据表显示错误“无法读取未定义的属性 aDatasort”
- ruby-on-rails - 如何将枚举与复选框导轨一起使用
- java - 我正在尝试从 Drawable 加载图像,但它没有在 imageview 中显示任何图像
- json - 如何从 JSON 数据文件创建新的 A-FRAME 对象/基元?