当一个组件加载时,我试图在React Native中使用AsyncStorage加载一个对象,但是useEffect创建了一个infitine循环,我发现的所有其他问题都告诉我使用componentWillMount,这似乎不再起作用。我尝试在组件呈现时调用puxaGastos(),以便可以将其传递给FlatList,但不知道如何调用它
const [gastos, setGastos] = useState()
const puxaGastos = async () => {
const gastosGuardados = await AsyncStorage.getItem('transacao')
const gastosParse = JSON.parse(gastosGuardados)
setGastos(gastosParse)
console.log(gastos)
}
return (<View style={styles.tela}><FlatList/></View>)发布于 2020-06-08 10:11:14
useCallback包装puxaGastos以防止递归重新呈现,并使用包含puxaGastos [puxaGastos]的依赖项在useEffect中调用它
const [gastos, setGastos] = useState()
const puxaGastos =useCallback(async () => {
const gastosGuardados = await AsyncStorage.getItem('transacao')
const gastosParse = JSON.parse(gastosGuardados)
setGastos(gastosParse)
console.log(gastos)
},[])
useEffect(() =>{
puxaGastos()
},[puxaGastos])
return (<View style={styles.tela}><FlatList/></View>)
puxaGastos inside useEffect with dependencies includes puxaGastos
const [gastos, setGastos] = useState()
useEffect(() =>{
const puxaGastos =async () => {
const gastosGuardados = await AsyncStorage.getItem('transacao')
const gastosParse = JSON.parse(gastosGuardados)
setGastos(gastosParse)
console.log(gastos)
}
puxaGastos()
},[puxaGastos])
return (<View style={styles.tela}><FlatList/></View>)
发布于 2020-06-10 22:50:37
使用react-native-easy-app,您可以在初始化完成后同步访问AsyncStroage,这可能是一个很好的方式。
import { XStorage } from 'react-native-easy-app';
import { AsyncStorage } from 'react-native';
export const RNStorage = {
token: undefined,
isShow: undefined,
userInfo: undefined
};
const initCallback = () => {
// From now on, you can write or read the variables in RNStorage synchronously
// equal to [console.log(await AsyncStorage.getItem('isShow'))]
console.log(RNStorage.isShow);
// equal to [ await AsyncStorage.setItem('token',TOKEN1343DN23IDD3PJ2DBF3==') ]
RNStorage.token = 'TOKEN1343DN23IDD3PJ2DBF3==';
// equal to [ await AsyncStorage.setItem('userInfo',JSON.stringify({ name:'rufeng', age:30})) ]
RNStorage.userInfo = {name: 'rufeng', age: 30};
};
XStorage.initStorage(RNStorage, AsyncStorage, initCallback); https://stackoverflow.com/questions/62252904
复制相似问题