我试图访问一个 api 并在每次单击按钮时简单地将对象(我从中获取)存储在状态中,但是一旦我尝试npm 启动它,它就会给出语法错误:这是一个保留字. 我不知道为什么会发生这种情况,我想要一些答案,如果您发现任何缺陷或改进我的代码的方法,请随时告诉我。这是代码:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class List extends React.Component {
constructor(props){
super(props);
this.state = {
personagens: [],
page: 1,
};
this.getNextPers = this.getNextPers.bind(this);
}
getNextPers(){
let URL = 'https://swapi.com/api/people/'+{this.state.page};
axios.get(URL).then((p) => this.setState({ personages: [...{this.state.personagens}, ...p], page: {this.state.page}+1 }));
}
render(){
return (
<div>
<p>Personagens</p>
{this.state.personagens.map(pers, i) => (
<div key={i}>
<p>{pers.name}</p>
</div>
)}
<button onClick={this.getNextPerson}>Proximo Personagem</button>
</div>
);
}
}
ReactDOM.render(<List />, document.getElementById('root'));