我是编码、 react native 和移动应用程序开发的新手。 我正在尝试构建水提醒应用程序。
我有 FAB 组按钮,显示不同类型的饮料。当用户单击第二个 FAB 按钮(汉堡菜单图标)时,它会打开,我想通过所选的水量设置状态。然后将此状态传递给进度圈来计算进度。
但是显然我无法正确更新状态,因为我收到一个错误,progress.circle 收到了 NaN 值
const goal = 2000;
export default class HomeScreen extends React.Component {
static navigationOptions = {
header: null
};
state = {
progress: 0,
drunk: 0,
open: false
};
drinkOther = drink => {
let bottle = 500;
let bigBottle = 1000;
let coffee = 200;
let tea = 200;
let progress = this.state.progress;
this.setState(prevState => ({
drunk: prevState.drunk + drink,
progress: (prevState.drunk + drink) / goal
}));
};
render() {
return (
<Provider>
<View style={styles.container}>
<View style={styles.buttonContainer}>
<Portal>
<FAB.Group
open={this.state.open}
icon={"menu"}
actions={[
{
icon: require("../assets/images/juice.png"),
label: "Juice",
onPress: this.drinkOther("juice")
},
{
icon: require("../assets/images/coffee.png"),
label: "Coffee",
onPress: this.drinkOther("coffee")
},
{
icon: require("../assets/images/tea.png"),
label: "Tea",
onPress: this.drinkOther("tea")
},
{
icon: require("../assets/images/big_bottle.png"),
label: "Big Bottle",
onPress: this.drinkOther("bigBottle")
},
{
icon: require("../assets/images/bottle.png"),
label: "Small Bottle",
onPress: this.drinkOther("bottle")
}
]}
onStateChange={({ open }) => this.setState({ open })}
onPress={() => {
this.setState({ open: !this.state.open });
}}
style={styles.fab}
color={"white"}
theme={{ colors: { accent: Colors.tintColor } }}
/>
</Portal>
</View>
</View>
</Provider>
);
}
最佳答案
看看 drinkOther
中的这个 setState
调用:
this.setState(prevState => ({
drunk: prevState.drunk + drink,
progress: (prevState.drunk + drink) / goal
}));
如果您查看 drink
的来源,就会发现它就是您传递给 drinkOther
的参数:
onPress: this.drinkOther("juice")
您尝试将字符串“juice”、“coffee”或其他内容添加到 drunk
总数中,然后将其除以一个数字,这当然会返回 NaN。
关于javascript - FAB 组按钮未设置状态 - React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54485364/