jas*_*tco 9 javascript scope reactjs
我有一个我正在创建的变量,我componentDidMount()希望它可用componentDidUpdate().有什么想法吗?代码如下所示:
class Example extends Component {
componentDidMount() {
const myVariable = 'this thing';
}
componentDidUpdate() {
// I'd like my variable to be accessible here
console.log(myVariable);
}
render() {...}
}
Run Code Online (Sandbox Code Playgroud)
Elo*_*pos 23
然后将其保存到组件中.
componentDidMount() {
this.myVariable = 'this thing';
}
componentDidUpdate() {
// I'd like my variable to be accessible here
console.log(this.myVariable);
}
Run Code Online (Sandbox Code Playgroud)
此外,正如@Gosha Arinich所指出的那样 - 请注意,如果您计划在整个组件的生命周期中重复使用此变量并更新它和/或进行渲染,则最好将其置于state组件(this.state)中.
| 归档时间: |
|
| 查看次数: |
9065 次 |
| 最近记录: |