【发布时间】:2020-09-12 05:12:06
【问题描述】:
我是原生反应新手,过去几个小时我一直在尝试解决这个问题。 我正在制作一个简单的费用跟踪器应用程序,我现在有 3 个组件,主屏幕、addexpensescreen 和 trackbudget。
从 addexpensescreen 添加新费用后,我在更新主屏幕上的总费用时遇到问题。我在 addexpensescreen 中使用 trackbudget 中的一个函数来调用其状态的更新。当我直接将状态分配给它的新费用时,它可以工作,但我必须手动刷新 Visual Studio 上的代码,然后才能将更改反映在应用程序上。所以我然后尝试使用 this.setState() 但出现警告并告诉我该组件已卸载。
到目前为止,这是我的代码。任何建议将不胜感激。谢谢!
跟踪预算屏幕:
代码
class TrackBudget extends React.Component {
constructor(props) {
super(props);
this.state = {
budget: 1000,
expenses: 500,
cat: []
};
}
updateExpenses(c) {
//works only when i refresh the app on the homescreen page
this.state.expenses += Number(c)
//does not work but I think this is the proper implementation
this.setState({ expenses: c + this.state.expenses})
}
budget() {
return this.state.budget
}
expenses() {
return this.state.expenses
}}
const budget = new TrackBudget()
export default budget
主屏幕:
代码
export default function HomeScreen(props) {
return {
<View style={styles.container}>
<ScrollView style={styles.container} contentContainerStyle={styles.contentContainer}>
{/* Add current expenses from trackbudget*/}
<Text style={styles.headerText}>Current Expenses for the Month: </Text>
<View>
//This is the place where I need the expense figure to be updated but it is not updating by itself
<Text style = {styles.expenseText}>${budget.expenses()}</Text>
</View>
添加费用屏幕:
代码
<BackBtn
onPress = { () => {this.reset(); alert("Submitted");
//updating the expenses with 50bucks
budget.updateExpenses(50)
}}></BackBtn>
【问题讨论】:
标签: reactjs react-native state react-props