javascript React 中的 this.state 与 state
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51118103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
this.state vs state in React
提问by J Seabolt
I'm working in a new codebase. Normally, I would set up state like this in a React component:
我正在一个新的代码库中工作。通常,我会在 React 组件中设置这样的状态:
class App extends React.Component {
constructor() {
super();
this.state={
foo: 'bar'
}
}
....
In this new codebase, I'm seeing a lot of this:
在这个新的代码库中,我看到了很多这样的内容:
class App extends React.Component {
state={
foo: 'bar'
}
....
Is there an advantage to doing it this way? They seem to only do it when state doesn't need to be altered. I always thought of state as being something React handled. Is this an ok thing to do?
这样做有好处吗?他们似乎只在不需要更改状态时才这样做。我一直认为状态是 React 处理的东西。这是可以做的事情吗?
采纳答案by Tholle
The end result of both approaches is the same. Both approaches are just setting the initial stateof the component. It's worth noting that class properties are a stage 3 proposal, so all development environments may not be able to use them.
两种方法的最终结果是相同的。这两种方法都只是设置state组件的初始值。值得注意的是,类属性是第 3 阶段的提案,因此所有开发环境可能无法使用它们。
I personally like to use the class field variant if nothing else is done in the constructor, as it is less code to write, and you have no supercall to worry about.
如果在构造函数中没有做任何其他事情,我个人喜欢使用类字段变体,因为它编写的代码更少,而且您无需super担心调用。
Example
例子
class Component1 extends React.Component {
state = { value: this.props.initialValue };
render() {
return <div> {this.state.value} </div>
}
}
class Component2 extends React.Component {
constructor(props) {
super(props);
this.state = { value: props.initialValue };
}
render() {
return <div> {this.state.value} </div>
}
}
function App() {
return (
<div>
<Component1 initialValue={1} />
<Component2 initialValue={2} />
</div>
);
}
回答by AmerllicA
Actually both of them bind to thispointer. the thisthat made in constructorof class.
实际上它们都绑定到this指针。的this是,在做constructor的class。
Totally you can access to local state by this.statebut in first style you can pass propsto constructorby superand then use it in statedeclaration, just like below:
完全你可以访问本地状态 bythis.state但在第一种样式中你可以传递props给constructorbysuper然后在state声明中使用它,如下所示:
class App extends React.Component {
constructor(props) {
super(props);
this.state={
foo: 'bar',
jaz: props.someParentState,
}
}
....
Awesome, you can access to propsin constructor, isn't pretty? I definitely use this style for local state declaration.
太棒了,你可以访问propsin constructor,是不是很漂亮?我绝对使用这种风格进行本地状态声明。
Hope this helps you.
希望这对你有帮助。

