React无法使用API​​调用读取未定义的属性状态

时间:2018-05-01 02:35:39

标签: javascript reactjs axios

我正在尝试使用简单的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 :(得分:2)

如果您使用的是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);
  });