[英]Reset component state in React Native
我只想重置某些(不是全部)状态的 state。 单击按钮时, present_count
、 total_count
、 present
和total
的值应设置为其初始值 state (0)。 而subjects
和text
的 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 值text
, subjects
:
// 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.