【问题标题】:Unable to update State in a component through a function call ReactNative无法通过函数调用 React Native 更新组件中的状态
【发布时间】: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


    【解决方案1】:

    使用箭头函数将函数正确绑定到当前上下文 -

      updateExpenses = (c) => { // arrow function syntax
        const expenses =  this.state.expenses + Number(c)
    
        this.setState({ expenses })
      }
    

    并直接引用状态值 -

    <Text style={styles.expenseText}>
      {this.state.expenses} // no need to call a function
    </Text>
    

    【讨论】:

    • 您好,感谢您的帮助。但是,我仍然面临 this.setState({expenses}) 无法使用已卸载组件更改状态的问题。我不确定如何解决这个问题..
    【解决方案2】:

    您的 TrackBudget 组件在哪里呈现?如果不挂载它,就无法更新组件实例的状态。如果要设置 TrackBudget 的状态,则需要对其进行渲染。

    不清楚这些组件是如何从您的代码中连接起来的。从第一遍开始,所有这些逻辑似乎都应该在您的主屏幕上,并且您可以将预算存储在主屏幕的状态中。然后单击按钮,您可以更新状态以反映您更新的费用。如果您需要按钮位于单独的屏幕上,则可以将 addExpenseScreen 设为 HomeScreen 的子项并传递回调以设置 HomeScreen 的状态。

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多