[英]How to log both prevState and original state in React?
I have a toggle switch that goes from true to false.我有一个从真到假的拨动开关。
flipSwitch = () => {
console.log(this.state)
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}))
}
Everything is working like it is supposed to, but I want to log both the prevState and original state at the same time.一切都按预期工作,但我想同时记录 prevState 和原始 state。 I tried below adding a callback function after setting the prevState, but then it breaks my toggle switch.
我在下面尝试在设置 prevState 后添加回调 function ,但随后它破坏了我的拨动开关。
flipSwitch = () => {
console.log(this.state)
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}, () => console.log(prevState)))
}
Thats not correct what you're trying to do at here那是不正确的,您在这里尝试做什么
flipSwitch = () => {
console.log(this.state)
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}, () => console.log(prevState)))
}
You won't have access to prevState
in 2nd parameter of setState.您将无法访问 setState 的第二个参数中的
prevState
。
You should modify your setState
function like this你应该像这样修改你的
setState
function
flipSwitch = () => {
console.log(this.state) // this refers to previous state here
this.setState(prevState => {
console.log(prevState) // prevState refers to previous state
return ({
isToggleOn: !prevState.isToggleOn
})
}, () => console.log(this.state) // here this refers to updated state)
}
Eg you can try比如你可以试试
import React from "react";
class App extends React.Component {
constructor() {
super();
this.state = {
isToggleOn: false
};
}
flipSwitch = () => {
console.log(this.state);
this.setState(
prevState => {
console.log("prevState", prevState);
return {
isToggleOn: !prevState.isToggleOn
};
},
() => {
console.log("setState Callback", this.state);
}
);
};
render() {
return (
<div className="App">
<button onClick={this.flipSwitch}>
{this.state.isToggleOn ? "Flipped" : "Flip Switch!"}
</button>
</div>
);
}
}
export default App;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.