this.state 与 React 中的状态对比
this.state vs state in React
我在新的代码库中工作。通常,我会在 React 组件中设置这样的状态:
class App extends React.Component {
constructor() {
super();
this.state={
foo: 'bar'
}
}
....
在这个新的代码库中,我看到了很多这样的东西:
class App extends React.Component {
state={
foo: 'bar'
}
....
这样做有好处吗?他们似乎只在不需要更改状态时才这样做。我一直认为状态是 React 处理的东西。这是一件好事吗?
实际上它们都绑定到 this
指针。在 class
的 constructor
中制作的 this
。
完全可以通过 this.state
访问本地状态,但在第一种样式中,您可以通过 super
将 props
传递给 constructor
,然后在 [=19] 中使用它=] 声明,如下所示:
class App extends React.Component {
constructor(props) {
super(props);
this.state={
foo: 'bar',
jaz: props.someParentState,
}
}
....
太棒了,你可以在 constructor
中访问 props
,是不是很漂亮?我绝对使用这种样式进行本地状态声明。
希望对您有所帮助。
两种方法的最终结果是一样的。这两种方法都只是设置组件的初始 state
。值得注意的是class properties are a stage 3 proposal,所以所有的开发环境可能都不能用
如果在构造函数中什么都不做,我个人喜欢使用 class 字段变体,因为它编写的代码更少,而且您无需担心 super
调用。
例子
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>
);
}
我在新的代码库中工作。通常,我会在 React 组件中设置这样的状态:
class App extends React.Component {
constructor() {
super();
this.state={
foo: 'bar'
}
}
....
在这个新的代码库中,我看到了很多这样的东西:
class App extends React.Component {
state={
foo: 'bar'
}
....
这样做有好处吗?他们似乎只在不需要更改状态时才这样做。我一直认为状态是 React 处理的东西。这是一件好事吗?
实际上它们都绑定到 this
指针。在 class
的 constructor
中制作的 this
。
完全可以通过 this.state
访问本地状态,但在第一种样式中,您可以通过 super
将 props
传递给 constructor
,然后在 [=19] 中使用它=] 声明,如下所示:
class App extends React.Component {
constructor(props) {
super(props);
this.state={
foo: 'bar',
jaz: props.someParentState,
}
}
....
太棒了,你可以在 constructor
中访问 props
,是不是很漂亮?我绝对使用这种样式进行本地状态声明。
希望对您有所帮助。
两种方法的最终结果是一样的。这两种方法都只是设置组件的初始 state
。值得注意的是class properties are a stage 3 proposal,所以所有的开发环境可能都不能用
如果在构造函数中什么都不做,我个人喜欢使用 class 字段变体,因为它编写的代码更少,而且您无需担心 super
调用。
例子
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>
);
}