簡體   English   中英

在 React Native 中重置組件 state

[英]Reset component state in React Native

我只想重置某些(不是全部)狀態的 state。 單擊按鈕時, present_counttotal_countpresenttotal的值應設置為其初始值 state (0)。 subjectstext的 state 應該保持不變。

constructor(props) {
    super(props);
    this.state = { 
      subjects: [],
      text: "",
      present_count: [0, 0, 0, 0, 0, 0, 0],
      total_count: [0, 0, 0, 0, 0, 0, 0],
      present: 0,
      total: 0
    }
}

編輯:我正在使用AsyncStorage保存修改后的 state。

您可以使用擴展運算符覆蓋當前的 state 值,然后使用當前的 state 值textsubjects

// default state 
const defaultState = {
  subjects: [],
  text: "",
  present_count: [0, 0, 0, 0, 0, 0, 0],
  total_count: [0, 0, 0, 0, 0, 0, 0],
  present: 0,
  total: 0
}

// component constructor.
constructor(props) {
    super(props);
    this.state = { ...defaultState };
}

// click event handler    
handleClick = () => {
  this.setState({
    ...defaultState,
    subjects: this.state.subjects,
    text: this.state.text
  });
}

您可以創建一個 object 存儲您的 state 您要重置的初始狀態 state,如下所示:

const initState = {
   total: 0,
   present: 0,
   present_count: [0, 0, 0, 0, 0, 0, 0],
   total_count: [0, 0, 0, 0, 0, 0, 0],
}

然后你可以

this.setState({
   ...initialState
})

在你的按鈕上 onClick

希望有所幫助。 ^^

使用展開運算符在這里可能會有用。

constructor(props) {
    super(props);
    this.defaultState = {
      present_count: [0, 0, 0, 0, 0, 0, 0],
      total_count: [0, 0, 0, 0, 0, 0, 0],
      present: 0,
      total: 0
    }
    this.state = { 
      subjects: [],
      text: "",
      ...defaultState,
    }
}
.
.
.
onClick = () => {
  this.setState({
    ...this.defaultState, // This will only pass in values from your defaultState and leave the others (subjects & text) alone
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM