我是新来的反应原生,现在我有一个问题。我正在尝试使用异步存储将我的数据保存到本地存储中,我正在关注这个tutorial ,
它工作正常但不在我的开关代码中。这是我的构造函数
constructor(props) {
super(props)
this.state = {prevBtn: undefined}
this.onPrevValueChange = this.onPrevValueChange.bind(this);
}
然后我在didMount中获取该项:
componentDidMount() {
this.getQuestionnaire();
AsyncStorage.getItem('prevBtn').then((value) => this.setState({ 'prevBtn': value }));
}
更改时设置值:
onPrevValueChange = (value) => {
AsyncStorage.setItem('prevBtn', value);
this.setState({ prevBtn: value });
}
和渲染方法:
render(){
const {}
return(
<Switch
value={prevBtn}
backgroundActive={'red'}
onValueChange={this.onPrevValueChange}
/>
);
}
有人可以帮忙吗?
与setState
在componentDidMount
中的问题,当你使用单引号设置prevBtn
的值时,所以它的行为类似于String
而不是state
,请使用如下:
componentDidMount() {
this.getQuestionnaire();
AsyncStorage.getItem('prevBtn').then((value) => this.setState({ prevBtn: value }));
}
在render
你直接使用prevBtn
,用它作为this.state.prevBtn
。
render(){
const {}
return(
<Switch
value={this.state.prevBtn}
backgroundActive={'red'}
onValueChange={this.onPrevValueChange}
/>
);
}
您需要将componentDidMount更改为:
请注意,AsyncStorage.getItem
始终返回一个字符串,您必须在使用它之前将其转换为布尔值。正如另一位评论者指出的那样,你不能在国家财产周围引用。
componentDidMount() {
this.getQuestionnaire();
AsyncStorage.getItem('prevBtn').then((value) => {
value === 'true'
? this.setState({ prevBtn: true })
: this.setState({ prevBtn: false })
});
}