1

我试图访问一个 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'));
4

2 回答 2

2

In let URL = 'https://swapi.com/api/people/'+{this.state.page}; the curly braces are the problem. Try either:

const URL = 'https://swapi.com/api/people/' + this.state.page

or

const URL = `https://swapi.com/api/people/${this.state.page}`

(both works)

I agree with the others that lowercase url might be a better choice for a variable name.

于 2018-05-25T11:58:44.200 回答
1

URL是变量名的错误选择,并且可能是您提到的错误中引用的保留字。也许选择更多类似的东西peopleApiEndpoint

一般反馈:

  • Use const as opposed to let, when declaring the aforementioned variable. You never make a reassignment to this variable. Read this as further reference material.
  • Don't use an index as a key when iterating over elements. pers.name would perhaps be a better choice of key. Read this as further reference material.
于 2018-05-25T11:54:32.383 回答