React:处理事件 - 参数可见性
React: Handling Events - parameter visibility
我正在关注 React 文档。在“Handling Events”部分,下面的代码段在那里。
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
在handleClick()
函数中,如何访问state
?为什么不this.state
?
因为它是函数参数。在这段代码中:
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
这部分是一个 arrow function,它将组件的先前状态作为参数:
state => ({
isToggleOn: !state.isToggleOn
})
和returns一个新的状态,触发重新渲染等等。
Why not this.state?
经验法则:如果你的下一个状态取决于上一个状态,你必须 使用这种方法来更新你的状态。所以你不会 运行 进入与 this.setState
调用的竞争条件,因为它是异步函数。
希望对您有所帮助:)
这就是 this.setState 的工作方式,它是为 this.setState()
传递的更新程序回调,根据反应 documentation:
Passing an update function allows you to access the current state
value inside the updater. Since setState calls are batched, this lets
you chain updates and ensure they build on top of each other instead
of conflicting
还可以找到更多信息 here。
我正在关注 React 文档。在“Handling Events”部分,下面的代码段在那里。
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
在handleClick()
函数中,如何访问state
?为什么不this.state
?
因为它是函数参数。在这段代码中:
handleClick() {
this.setState(state => ({
isToggleOn: !state.isToggleOn
}));
}
这部分是一个 arrow function,它将组件的先前状态作为参数:
state => ({
isToggleOn: !state.isToggleOn
})
和returns一个新的状态,触发重新渲染等等。
Why not this.state?
经验法则:如果你的下一个状态取决于上一个状态,你必须 使用这种方法来更新你的状态。所以你不会 运行 进入与 this.setState
调用的竞争条件,因为它是异步函数。
希望对您有所帮助:)
这就是 this.setState 的工作方式,它是为 this.setState()
传递的更新程序回调,根据反应 documentation:
Passing an update function allows you to access the current state value inside the updater. Since setState calls are batched, this lets you chain updates and ensure they build on top of each other instead of conflicting
还可以找到更多信息 here。