![](/img/trans.png)
[英]Cannot access this.state or this.props outside the .then(json) fetch call unless i wrap console.log(this.state) inside setTimeout
[英]If i can access and use the this.props & this.state directly then why i have to call them via the super(props) in constructor in react native?
假设我有一个类组件myPapa ,其中没有使用任何构造函数或super() :
class myPapap extends React.Component{
render(){
this.state = {mom: 'dad'};
this.props.brother = 'sister';
alert(this.state + ' ' + this.props);
return(
<View>
Something ...
</View>
);
}
}
哪个工作完美,并发出警报:
[object Object][object Object]
这意味着我们可以调用this.props和this.state并可以正常工作。 所以,如果这件事正在工作,那我为什么要做:
class myPapap extends React.Component{
constructor(props){
super(props);
this.state = {mom: 'dad'};
this.props.brother = 'sister';
}
}
请任何人用示例简单地说明一下?
您的示例都不正确。 您不允许修改组件收到的props
对象( documentation ),因此:
this.props.brother = 'sister';
在两个地方都不正确。 从容器中传递brother
道具,或者使brother
成为国家财产,而不是道具财产。
另外,在第二个示例中, this.state = ...
不正确。 除了构造函数( 文档 )之外,不允许将其直接分配给this.state
。
关于为什么必须拥有super(props)
:这是因为这是设置this.props
,而React框架依赖于您执行此操作,而从不直接更改props
( props
属性所指向的对象或该对象的状态宾语)。
可以分配this.state的唯一地方是构造函数。
众所周知,我们在React组件中使用state
的原因是,只要组件的状态已更新,就会触发组件的重新渲染,以便其表示能够反映组件的状态。 为了利用组件state
提供的这一优势,我们必须服从该机制。
而且,仅当我们使用setState()
方法以适当的方式更新组件的状态时,重新渲染过程才会发生。
有关更多信息,您可以在这里找到它: 不要直接修改状态
您的代码this.props.brother = 'sister';
肯定无法正常工作。
这是演示: https : //codesandbox.io/s/j354ypk645
您将收到错误:
无法添加属性兄弟,对象不可扩展
原因是,根据React Document Props是Readable ,他们说:
道具是只读的
无论您将组件声明为函数还是类,它都绝不能修改自己的道具。
...
就其道具而言,所有React组件都必须像纯函数一样工作。
根据React文档中的Constructor()部分的说法:
如果您不初始化状态并且不绑定方法,则无需为React组件实现构造函数。
和
React组件的构造函数在挂载之前被调用。 在为React.Component子类实现构造函数时,应在其他任何语句之前调用super(props)。 否则,this.props将在构造函数中未定义,这可能会导致错误。
那么,您可以使用this.props.brother
来检索从父组件传递的此属性的值。 但是,这仅用于get
,您不应为其set
值。 原因已在此答案的第二部分中进行了解释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.