Reactjs 使用useReducer时,如何从AsyncStorage获取数据并将其添加到初始状态?

Reactjs 使用useReducer时,如何从AsyncStorage获取数据并将其添加到初始状态?,reactjs,react-native,async-await,react-hooks,asyncstorage,Reactjs,React Native,Async Await,React Hooks,Asyncstorage,我正在使用Hooks&AsyncStorage.setItem中的useContext和useReducer在更新状态时保存数据。在重新加载应用程序时,我希望确保使用AsyncStorage.getItem获取保存的数据,并将其添加到初始状态 我尝试将异步作为第三个属性的init函数添加到useReducer中,但仍然没有用接收到的数据替换初始数据。请阅读下面的代码和帮助 提前谢谢你 可以将数据保存到异步存储的当前代码 const [user, dispatch] = useReducer(

我正在使用Hooks&AsyncStorage.setItem中的useContextuseReducer在更新状态时保存数据。在重新加载应用程序时,我希望确保使用AsyncStorage.getItem获取保存的数据,并将其添加到初始状态

我尝试将异步作为第三个属性的init函数添加到useReducer中,但仍然没有用接收到的数据替换初始数据。请阅读下面的代码和帮助

提前谢谢你

可以将数据保存到异步存储的当前代码

  const [user, dispatch] = useReducer(userReducer, {});

  useEffect(() => {
    AsyncStorage.setItem('user', JSON.stringify(user))
  }, [user]);

  return(
    <UserContext.Provider value={{user,dispatch}}>
      {props.children}
    </UserContext.Provider>
  );
}
const[user,dispatch]=useReducer(userReducer,{});
useffect(()=>{
AsyncStorage.setItem('user',JSON.stringify(user))
},[用户];
返回(
{props.children}
);
}
下面是我尝试过的代码,但无法将现有数据保存为初始数据

const getUser = async function() {
  const userData = await AsyncStorage.getItem('user')
  console.log("parse");
  console.log(userData);
  console.log("parsed data");
  console.log(JSON.parse(userData));
  return userData ? JSON.parse(userData) : {};
}

export const UserContext = createContext();

const UserContextProvider = (props) => {
  const [user, dispatch] = useReducer(userReducer, {}, getUser);

  useEffect(() => {
    console.log("context");
    console.log(JSON.stringify(user));
    AsyncStorage.setItem('user', JSON.stringify(user))
  }, [user]);

  return(
    <UserContext.Provider value={{user,dispatch}}>
      {props.children}
    </UserContext.Provider>
  );
}
const getUser=async function(){
const userData=await AsyncStorage.getItem('user'))
console.log(“解析”);
console.log(userData);
日志(“解析数据”);
log(JSON.parse(userData));
返回userData?JSON.parse(userData):{};
}
export const UserContext=createContext();
const UserContextProvider=(props)=>{
const[user,dispatch]=useReducer(userReducer,{},getUser);
useffect(()=>{
console.log(“上下文”);
log(JSON.stringify(user));
AsyncStorage.setItem('user',JSON.stringify(user))
},[用户];
返回(
{props.children}
);
}

您的用户初始状态需要同步。因为asyncStorage不是同步API,所以实际上不能将值作为initialState传递

但是,您可以使用
useffect加载状态
,如下所示

const getUser = async () => {
   try {
       const user = await AsyncStorage.getItem('user')
       return user ? JSON.parse(user) : {};
   } catch (e) {
       console.log('Failed to fetch the data from storage');
   }
}

export const UserContext = createContext();

const UserContextProvider = (props) => {
  const [isLoading, setIsLoading] = useState(true);
  const [user, dispatch] = useReducer(userReducer, {});

  // Loading initial Satte
  useEffect(() => {
     async function fetchUser() {
         const user = await getUser();
         setIsLoading(false);
         dispatch({type: 'INIT_REDUCER', user}); // You must handle initReducer in reducer
     }
     fetchUser();
 }, []);

  useEffect(() => {
    if(user) {
        // This check is required to avoid initial writing to asyncStorage
        console.log("context");
        console.log(JSON.stringify(user));
        AsyncStorage.setItem('user', JSON.stringify(user))
    }
  }, [user]);

  if(isLoading) {
     return (
       <View> 
           <Text>Loading...</Text> 
       </View>
     );
  }
  return(
    <UserContext.Provider value={{user,dispatch}}>
      {props.children}
    </UserContext.Provider>
  );
} 
const getUser=async()=>{
试一试{
const user=await AsyncStorage.getItem('user'))
返回用户?JSON.parse(用户):{};
}捕获(e){
console.log('未能从存储器中获取数据');
}
}
export const UserContext=createContext();
const UserContextProvider=(props)=>{
const[isLoading,setIsLoading]=useState(true);
const[user,dispatch]=useReducer(userReducer,{});
//加载初始状态
useffect(()=>{
异步函数fetchUser(){
const user=wait getUser();
设置加载(假);
dispatch({type:'INIT_REDUCER',user});//必须在REDUCER中处理initReducer
}
fetchUser();
}, []);
useffect(()=>{
如果(用户){
//需要此检查以避免初始写入异步存储
console.log(“上下文”);
log(JSON.stringify(user));
AsyncStorage.setItem('user',JSON.stringify(user))
}
},[用户];
如果(孤岛加载){
返回(
加载。。。
);
}
返回(
{props.children}
);
} 

您的用户初始状态需要同步。因为asyncStorage不是同步API,所以实际上不能将值作为initialState传递

但是,您可以使用
useffect加载状态
,如下所示

const getUser = async () => {
   try {
       const user = await AsyncStorage.getItem('user')
       return user ? JSON.parse(user) : {};
   } catch (e) {
       console.log('Failed to fetch the data from storage');
   }
}

export const UserContext = createContext();

const UserContextProvider = (props) => {
  const [isLoading, setIsLoading] = useState(true);
  const [user, dispatch] = useReducer(userReducer, {});

  // Loading initial Satte
  useEffect(() => {
     async function fetchUser() {
         const user = await getUser();
         setIsLoading(false);
         dispatch({type: 'INIT_REDUCER', user}); // You must handle initReducer in reducer
     }
     fetchUser();
 }, []);

  useEffect(() => {
    if(user) {
        // This check is required to avoid initial writing to asyncStorage
        console.log("context");
        console.log(JSON.stringify(user));
        AsyncStorage.setItem('user', JSON.stringify(user))
    }
  }, [user]);

  if(isLoading) {
     return (
       <View> 
           <Text>Loading...</Text> 
       </View>
     );
  }
  return(
    <UserContext.Provider value={{user,dispatch}}>
      {props.children}
    </UserContext.Provider>
  );
} 
const getUser=async()=>{
试一试{
const user=await AsyncStorage.getItem('user'))
返回用户?JSON.parse(用户):{};
}捕获(e){
console.log('未能从存储器中获取数据');
}
}
export const UserContext=createContext();
const UserContextProvider=(props)=>{
const[isLoading,setIsLoading]=useState(true);
const[user,dispatch]=useReducer(userReducer,{});
//加载初始状态
useffect(()=>{
异步函数fetchUser(){
const user=wait getUser();
设置加载(假);
dispatch({type:'INIT_REDUCER',user});//必须在REDUCER中处理initReducer
}
fetchUser();
}, []);
useffect(()=>{
如果(用户){
//需要此检查以避免初始写入异步存储
console.log(“上下文”);
log(JSON.stringify(user));
AsyncStorage.setItem('user',JSON.stringify(user))
}
},[用户];
如果(孤岛加载){
返回(
加载。。。
);
}
返回(
{props.children}
);
} 
谢谢! 根据以下建议更新并运行代码,但有微小更改

const getUser = async () => {
  try {
    const user = await AsyncStorage.getItem('user')
    return user ? JSON.parse(user) : {};
  } catch (e) {
    console.log('Failed to fetch the data from storage');
  }
}
export const UserContext = createContext();

const UserContextProvider = (props) => {
  const [user, dispatch] = useReducer(userReducer, {});

  // Loading initial Satte
  useEffect(() => {
     async function fetchUser() {
       const user = await getUser();
       dispatch({type: 'ADD_USER', user});
     }
     fetchUser();
  }, []);

  // Update AsyncStorage when user is updated
  useEffect(() => {
    // This check is required to avoid initial writing to asyncStorage
    if(user) {
        AsyncStorage.setItem('user', JSON.stringify(user))
    }
  }, [user]);


  return(
    <UserContext.Provider value={{user,dispatch}}>
      {props.children}
    </UserContext.Provider>
  );
}
const getUser=async()=>{
试一试{
const user=await AsyncStorage.getItem('user'))
返回用户?JSON.parse(用户):{};
}捕获(e){
console.log('未能从存储器中获取数据');
}
}
export const UserContext=createContext();
const UserContextProvider=(props)=>{
const[user,dispatch]=useReducer(userReducer,{});
//加载初始状态
useffect(()=>{
异步函数fetchUser(){
const user=wait getUser();
分派({type:'ADD_USER',USER});
}
fetchUser();
}, []);
//更新用户时更新异步存储
useffect(()=>{
//需要此检查以避免初始写入异步存储
如果(用户){
AsyncStorage.setItem('user',JSON.stringify(user))
}
},[用户];
返回(
{props.children}
);
}
谢谢! 根据以下建议更新并运行代码,但有微小更改

const getUser = async () => {
  try {
    const user = await AsyncStorage.getItem('user')
    return user ? JSON.parse(user) : {};
  } catch (e) {
    console.log('Failed to fetch the data from storage');
  }
}
export const UserContext = createContext();

const UserContextProvider = (props) => {
  const [user, dispatch] = useReducer(userReducer, {});

  // Loading initial Satte
  useEffect(() => {
     async function fetchUser() {
       const user = await getUser();
       dispatch({type: 'ADD_USER', user});
     }
     fetchUser();
  }, []);

  // Update AsyncStorage when user is updated
  useEffect(() => {
    // This check is required to avoid initial writing to asyncStorage
    if(user) {
        AsyncStorage.setItem('user', JSON.stringify(user))
    }
  }, [user]);


  return(
    <UserContext.Provider value={{user,dispatch}}>
      {props.children}
    </UserContext.Provider>
  );
}
const getUser=async()=>{
试一试{
const user=await AsyncStorage.getItem('user'))
返回用户?JSON.parse(用户):{};
}捕获(e){
console.log('未能从存储器中获取数据');
}
}
export const UserContext=createContext();
const UserContextProvider=(props)=>{
const[user,dispatch]=useReducer(userReducer,{});
//加载初始状态
useffect(()=>{
异步函数fetchUser(){
const user=wait getUser();
分派({type:'ADD_USER',USER});
}
fetchUser();
}, []);
//更新用户时更新异步存储
useffect(()=>{
//这张支票是必需的