React Не удается прочитать состояние свойства undefined с помощью вызова API - PullRequest
0 голосов
/ 01 мая 2018

Я пытаюсь заставить работать простой вызов API, где компонент вызывает API как его монтирование и устанавливает состояние, которое будет отображаться. Но когда я пытаюсь получить состояние, чтобы изменить объект в нем, он говорит, что состояние не определено.

TypeError: Невозможно прочитать свойство 'state' из неопределенного

class SpellGrid extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            value: '',
            spacing: '16',
            username: 'admin',
            password: 'notpassword',
            description: '',
            remember: false,
            spell: {
                name: '',
                school: '',
            },
        };

        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.mapApiToState = this.mapApiToState.bind(this);

    }

    mapApiToState() {
          // I've tried with all of the axios code in here.
    }


    componentDidMount() {

        axios
            .get("http://localhost:8000/api/spells/1")
            .then(function(response) {
                console.log('response', response);
                let fields = response.data[0].fields;
                // THIS IS THE LINE THAT IS ERRORING
                let spell = Object.assign({}, this.state.spell);

                spell.name =  fields.Name;
                spell.school =  fields.School;

                console.log('spell', spell);

                this.setState({spell});    

                console.log('state.spell', this.state.spell);
                //console.log('state', this.state);
            })
            .catch(function(error) {
                console.log(error);
            });

        console.log('state', this.state);
    }


    handleChange = name => event => {
        this.setState({
            [name]: event.target.value,
        });
    };


    onSubmit = (event) => {
        event.preventDefault();
        this.props.onSubmit(this.state.username, this.state.password)
    };


    handleSubmit(e) {
        console.log('Form state: ', this.state);
        e.preventDefault();
    }

    render() {
        const {classes, theme} = this.props;
        const { spacing } = this.state;

        return (
            <div>{this.state.spell.name}</div>
        );
    }
} export default withStyles(styles, { withTheme: true })(SpellGrid);

1 Ответ

0 голосов
/ 01 мая 2018

Если вы используете this, вам нужно быть осторожным, в какой области функций вы находитесь:

axios
  .get("http://localhost:8000/api/spells/1")
  .then(response => {
    // Since the `response` is now an arrow  function, we still
    // get access to the original `this`
    let fields = response.data[0].fields;
    let spell = Object.assign({}, this.state.spell);
    spell.name = fields.Name;
    spell.school = fields.School;
    this.setState({ 
      spell 
    });
  })
  .catch(error => {
    console.log(error);
  });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...