无法将获取的上下文提供者中的值用作我的useState的输入

问题描述

简短版本:

我在ContextProvider中有一个useEffect,可从服务器中获取一些数据。在我的组件中 使用此上下文,并希望使用“传入”数据初始化另一个useState()-hook。中的值 [value,setValue] = useState(dataFromContext)不会使用dataFromContext进行设置/初始化。为什么,为什么?

非常长的版本:

我正在尝试(并扩展)this example中如何在react中使用context / useContext-hook

所以,我有一个AppContext和一个ContextProvider,我将它包装在index.js中,示例中的所有内容都很好用。

现在我想在ContextProvider中的useEffect中加载数据,所以我的上下文提供者现在看起来像这样

const AppContextProvider = ({ children }) => {
  const profileInfoUrl = BASE_URL + `users/GetCurrentUsersProfileInfo/`
  const {loading,getTokenSilently} = useAuth0();  

  const [profileInfo,setProfileInfo] = useState( {})


  useEffect(() => {          
    if (!loading && profileInfo.user.username  === '' ) {                 
        Communication.get(profileInfoUrl,getTokenSilently,setProfileInfo); 
    }
 },[loading,getTokenSilently])
 
  
  const context = {
    profileInfo,setProfileInfo
  };
  return (
    <AppContext.Provider value={ context }> 
      {children}
    </AppContext.Provider>
  );
}

现在,我要在组件中显示此数据。其中之一是用户选择的类别,一个ID和isSelected列表,应提供一个复选框列表。

const TsProfileSettingsPage = ( ) => {
  //..  
  const { profileInfo,setProfileInfo } = useContext(AppContext);  
  const userCategories = Object.assign({},...profileInfo.userDetails.categories.map((c) => ({[c.id]: c})));
  const [checkedCategories,setCheckedCategories] = useState(userCategories);
 
  console.log("profileInfo.userDetails.categories : " + JSON.stringify(profileInfo.userDetails.categories));   
  console.log("userCategories : " + JSON.stringify(userCategories));//correct dictionary
  console.log("checkedCategories : " + JSON.stringify(checkedCategories)); //empty object!
 //...rest of code

因此,我加载用户选择并将其转换为以“ userCategories”结尾的字典。我使用该“ userCategories”来初始化checkedCategories。但是,在下面的console.logs中,userCategories设置正确,但checkedCategories没有设置,它变为空对象!

所以我的问题是。我在这里想错了吗? (显然我是),我只想拥有一个外部状态。 一切正常,但是当我在组件中使用它初始化useState()时,它不会被设置。我已经测试过在组件中具有另一个useEffect(),但是我只是觉得Im正在做一些更基本的错误。

感谢您的帮助

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...