首页 > 解决方案 > 将现有上下文传递给我的 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)。这可能吗,如果可以,我该怎么写?

标签: javascriptreactjscurryinguse-context

解决方案


从返回的 set 函数useState()允许您像这样传递一个函数,所以实际上不需要更改我的代码来允许这种情况发生,它已经工作了


推荐阅读