我正在尝试使用global关键字从函数中修改全局变量,但是当我尝试这样做时,出现错误““ SyntaxError:在全局声明之前使用名称'a'”
class Homebase extends Component {
render() {
return (
<section>
{ /* other elements */ }
<div className="container-about">
<Demo/>
</div>
</section>
)
}
}
class Demo extends Component {
constructor(props) {
super(props);
this.state = {
pictures: [], // start them off empty, you can populate them later
}
}
handleShuffleClick() {
this.setState({pictures: shuffle(pictures)}); // where 'shuffle' is a function that shuffles
}
render() {
const pictureElements = this.state.pictures.map(picture => (
<Picture pictureData={ picture }/>
))
return (
<div id="grid" className="row-about my-shuffle-container-about">
<div className="col-1@sm col-1@xs my-sizer-element">
<button onClick={ this.handleShuffleClick }>Shuffle!</button>
<div className="pictures-container">
{ pictureElements }
</div>
</div>
</div>
)
}
}
class Picture extends Component {
render() {
// define how each Picture element displays in HTML from given data (through this.props)
return (
<div>
{ this.props.pictureData.title }
</div>
)
}
}
预期结果:19 11
错误:“语法错误:名称'a'在全局声明之前使用”
答案 0 :(得分:1)
您必须先在函数中声明a
为全局变量,然后才能在函数中对其进行修改。因此您的代码应如下所示:
a=10 ## Global variable
def Global_modify():
global a
a=19
print(a)
a=11
print(a)
现在,即使您在函数之外要求a
的值,也将获得在函数中定义的任何值。
答案 1 :(得分:0)
为避免SyntaxError异常,您将无法使用全局声明。您仍然可以访问全局变量,但是:
a=10 ## Global variable
def Global_modify():
a=19
print(a)
globals()['a'] = 11
Global_modify()
print(a)
19
11