拉取挂载数据时的未定义状态

时间:2017-02-07 19:15:23

标签: javascript reactjs

我从我的数据库中提取数据,这些数据需要在安装组件之前可用,以便使用componentDidMount()生命周期方法填充页面。我已经验证了如果我删除了setState和console.log我的数据,它会按预期从数据库中获取,但是当我尝试将数据分配给我的状态变量时,它会返回一个错误,指出Unable to get property 'setState' of undefined or null reference内我的componentWillMount()生命周期方法。我在下面列出了我的ReactJS代码。

import React, { Component, PropTypes } from 'react';
import Picture from '../../components/picture.jsx';
import { browserHistory } from 'react-router';
export default class Products extends Component {

    constructor(props) {
      super(props);
      this.state = {clothingData: ''};
    }

    componentWillMount(){
            fetch('/t')
            .then(function(result){
              return result.json();
            })
            .then(function(re){
              this.setState({ clothingData: re });
              console.log(this.state.clothingData);
            })
            .catch(function(error){
                console.log(error);
            });
    }

    componentDidMount(){

        //empty for now
    }

    render(){
        var MyArray = ['justin','tiffany','joe','john','karissa','pam','joseph','sean','kim'];
        var imageSrc = ['http://placehold.it/249x373','http://placehold.it/249x373','http://placehold.it/249x373','http://placehold.it/249x373','http://placehold.it/249x373',
                        'http://placehold.it/249x373', 'http://placehold.it/249x373', 'http://placehold.it/249x373']; 

    return (
      <div>
        <Picture src = {imageSrc} onClick = { () => {browserHistory.push('/Product'); }} name = {MyArray} amount = {8} />
      </div>
  );
 }
}

1 个答案:

答案 0 :(得分:1)

问题是this正从组件实例重新分配给函数实例/全局对象。

componentWillMount() {
  fetch('/t')
    .then((result) => {
      return result.json();
    })
    .then((re) => {
      this.setState({ clothingData: re });
      console.log(this.state.clothingData);
    })
    .catch(function(error){
        console.log(error);
    });
}

将正常工作,因为箭头函数将确保this绑定到组件实例,因此实际将定义this.setState。您将this设置为没有setState属性的全局对象