【发布时间】:2019-06-14 10:15:10
【问题描述】:
在我的本机反应程序中,我有一个组件 (Bell),它为从 API 调用的每个项目/列表调用。铃铛用于在按下时发出通知(并取消它),我创建了一个状态(isBellActive)来确定铃铛是否已打开。如果是,则 isBellActive 为真,否则为假。我通过 asyncStorage 存储数据。
我遇到的问题是,如果我更改一个铃铛的状态(在一个项目/列表上)然后关闭应用程序并重新启动,该铃铛的状态更改将影响所有其他铃铛组件的 isBellActive 状态。如何使状态(即使它们都共享相同的名称)保留在一个特定的项目/列表中
铃铛组件类
export default class Bell extends React.Component {
constructor(props) {
super(props);
this.state = {
isBellActive: null,
};
}
componentDidMount = ()=>{
AsyncStorage.getItem('isBellActive').then(value => this.setState({ isBellActive: JSON.parse(value) }));
}
setTrue(){
AsyncStorage.setItem('isBellActive', JSON.stringify(true)).then(() => {
this.setState({ isBellActive: true});
});
}
setFalse(){
AsyncStorage.setItem('isBellActive', JSON.stringify(false)).then(() => {
this.setState({ isBellActive: false});
});
}
render() {
return (
<Ionicons
name={this.state.isBellActive? "md-notifications":"md-notifications-off"}
color={"white"}
size={30}
style={styles.NotifIcon}
onPress={() => {
Vibration.vibrate()
if(this.state.isBellActive == false){
PushNotificationIOS.scheduleLocalNotification({
userInfo:{
ID: this.state.ID
},
alertTitle: "Launching Soon:",
alertBody: this.state.alertBody,
fireDate: this.state.fireDate // in 30 mins
});
this.setTrue()
this.setState({Key:true})
}
else if(this.state.isBellActive != false){
PushNotificationIOS.cancelLocalNotifications({ID:this.state.ID});
this.setFalse()
}
}
}
}}
/>
);
}
}
调用组件的类
export default class LaunchingScreen extends React.Component{
let launches = this.state.dataSource.map((item, key) => {
..
<View>
..
<Bell />
..
</View>
..
}
}
更新 这是在调用组件的类中,它得到一个包含所有信息的 JSON:
componentDidMount(){
return fetch("https://launchlibrary.net/1.4/launch/next/20")
.then(response => response.json())
.then(responseJson => {
this.setState({
isLoading: false,
dataSource: responseJson.launches
});
})
.catch(error => {
console.log(error);
});
}
【问题讨论】:
-
由于每个
Bell组件都在访问AsyncStorage中的相同键isBellActive,因此在重新启动时每个组件都具有最后更新的值。您需要为每个组件分开AsyncStorage的键。dataSource记录长什么样,它们有什么唯一可识别的属性吗? -
datasource 从 API 获取一个 JSON 文件,并且创建的每个列表都有自己的名称,彼此不同...我发个图片和代码是什么样的
标签: react-native async-await components local-storage