我正在尝试获取组件的持久状态。
使用控制台日志,我可以看到 AsyncStorage 似乎保存和加载该值,并且该值似乎已正确字符串化/解析。
状态似乎也根据从存储加载的值正确更新。
但是,<SegmentedControlTab>
组件永远不会显示正确的 selectedIndex
;它总是默认为 0 或我手动分配给状态的任何值。我预计一旦状态在 componentDidMount
中更新,函数 <SegmentedControlTab>
会自动更新selectedIndex
反射(reflect)这一点:
import React, { Component } from 'react';
import { Text, ScrollView, AsyncStorage } from 'react-native';
import SegmentedControlTab from 'react-native-segmented-control-tab';
class Home extends Component {
state = {
//units: 1 //0=metric, 1=Imperial, 2=cups
};
componentDidMount = () => { //Load unit setting
AsyncStorage.getItem('units').then((value) => {
if (JSON.parse(value) === 0 || JSON.parse(value) === 1 || JSON.parse(value) === 2) {
this.setState({ units: JSON.parse(value) });
}
console.log('Value loaded: ', JSON.parse(value));
console.log('State: ', this.state.units);
});
}
render() {
return (
<ScrollView>
<Text style={{ marginTop: 20, fontSize: 20 }}>Settings and that.</Text>
<SegmentedControlTab
values={['Metric', 'Imperial', 'Cups']}
// tabStyle={{ borderColor: styleBackground }}
// activeTabStyle={{ backgroundColor: styleBackground, borderColor: styleBackground }}
selectedIndex={this.state.units}
onTabPress={async (event) => {
try {
await AsyncStorage.setItem('units', JSON.stringify(event));
} catch (error) {
console.log('Some kind of terrible error');
}
this.setState({ units: event });
console.log('Current state unit: ', this.state.units);
}}
/>
</ScrollView>
);
}
}
export default Home;
有什么建议我哪里出错了吗?
最佳答案
看起来这是第 3 方控件未按预期工作的情况; React Native 的 <SegmentedControlIOS>
控制按预期工作(类似于)上述代码。我想我需要玩一下 <SegmentedControlTab>
或者寻找替代方案...
关于javascript - React Native 中的持久状态 : setting state from AsyncStorage doesn't update component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43653759/