在下面的代码中,当我通过解构声明变量字符时
const { characters } = this.state;
我收到意外的令牌错误。
import React, { Component } from "react";
import Table from "./Table";
class App extends Component {
state = {
characters: [
{
name: "Charlie",
job: "Janitor"
},
{
name: "Mac",
job: "Bouncer"
},
{
name: "Dee",
job: "Aspring actress"
},
{
name: "Dennis",
job: "Bartender"
}
]
};
removeCharacter = index => {
const { characters } = this.state;
this.setState({
characters: characters.filter((character, i) => {
return i !== index;
})
});
};
const { characters } = this.state;
render() {
return (
<React.Fragment>
<div className="App">
<h1>Hello, React!</h1>
</div>
<div className="container">
<Table
characterData={characters}
removeCharacter={this.removeCharacter}
/>
</div>
</React.Fragment>
);
}
}
export default App;
这是代码的沙盒:sandbox with the error, look at the app.js file
当我将声明放入render函数中时,没有问题, 查看correct代码沙箱。
同样,当我在render函数(位于App.js文件的函数之外)中创建变量时,没有使用const或例如:
x=1;
当我在render函数中以this.x的形式使用它时,它工作正常,但是当我用let,const或var声明它时,会抛出意外的令牌错误。
您如何解释这种行为?
答案 0 :(得分:0)
您已在render方法之外破坏了字符。
import React, { Component } from "react";
import Table from "./Table";
class App extends Component {
state = {
characters: [
{
name: "Charlie",
job: "Janitor"
},
{
name: "Mac",
job: "Bouncer"
},
{
name: "Dee",
job: "Aspring actress"
},
{
name: "Dennis",
job: "Bartender"
}
]
};
removeCharacter = index => {
const { characters } = this.state;
this.setState({
characters: characters.filter((character, i) => {
return i !== index;
})
});
};
render() {
const { characters } = this.state;
return (
<React.Fragment>
<div className="App">
<h1>Hello, React!</h1>
</div>
<div className="container">
<Table
characterData={characters}
removeCharacter={this.removeCharacter}
/>
</div>
</React.Fragment>
);
}
}
export default App;