在没有构造函数的情况下的初始状态 [英] init state without constructor in react
问题描述
import React, { Component } from 'react';
class Counter extends Component {
state = { value: 0 };
increment = () => {
this.setState(prevState => ({
value: prevState.value + 1
}));
};
decrement = () => {
this.setState(prevState => ({
value: prevState.value - 1
}));
};
render() {
return (
<div>
{this.state.value}
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
</div>
)
}
}
通常,我看到的是如果人们使用es6类,则可以在构造函数中执行this.state.如果不是,他可能会使用getinitialstatestate函数放置状态.但是上面的代码(是的,这是一个有效的代码),两者都没有使用.我有2个问题,这里的状态是什么?那是局部变量吗?如果是,为什么没有const
? prevState来自哪里?为什么在setState中使用箭头功能? this.setState({value:'something'})
难道不是很容易吗?
Usually what I saw is people do this.state within the constructor function if he used es6 class. If he isn't he probably put the state using getinitialstate function. But above code (yes it's a working code), did not used either both. I have 2 question, what is state here? is that a local variable? if yes why it has no const
? where does the prevState come from? why arrow function is used in setState? isn't it's easy to just do this.setState({value:'something'})
?
推荐答案
否,这不是局部变量.等同于在构造函数中声明
this.state
.是的,在这种情况下,您可以只使用
this.setState({ value: this.state.value + 1 })
,结果将是相同的.Yes in that case you can just use
this.setState({ value: this.state.value + 1 })
, the result will be the same.但是请注意,使用功能性
setState
可以带来一些好处:But note that by using functional
setState
you can have some benefits:
如果在外部声明setState函数,则可以重新使用它:
the setState function can be reused if you declare it outside:
const increment = prevState => ({ value: prevState.value + 1 })
现在,如果您有几个组件需要使用此功能,则只需在任何地方导入和重用逻辑即可.
now if you have several components need to use this function, you can just import and reuse the logic everywhere.
this.setState(increment)
反应压扁多个
setState
并批量执行.这可能会导致一些意外的行为.请参见以下示例:React squashes several
setState
and executes them in batch. This may cause some unexpected behaviors. Please see the following example:http://codepen.io/CodinCat/pen/pebLaZ
add3 () { this.setState({ count: this.state.count + 1 }) this.setState({ count: this.state.count + 1 }) this.setState({ count: this.state.count + 1 }) }
执行此功能,
count
将仅加1executing this function the
count
will only plus 1如果使用功能性setState:
If you use functional setState:
http://codepen.io/CodinCat/pen/dvXmwX
const add = state => ({ count: state.count + 1 }) this.setState(add) this.setState(add) this.setState(add)
计数将按预期增加3.
您可以在此处查看文档: https://facebook.github .io/react/docs/react-component.html#setstate
You can see the docs here: https://facebook.github.io/react/docs/react-component.html#setstate
这篇关于在没有构造函数的情况下的初始状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!