获取错误:无法读取未定义的属性状态

时间:2017-10-31 02:34:50

标签: reactjs undefined state typeerror

import React, { Component } from "react";
import FormUpdate from "../components/formUpdate";
import { fetchClothingItem, updateClothingItem } from "../actions/crud";

export default class Update extends Component {
    constructor(props) {
        super(props);

        this.state = {
          updateClothingItem: {}
        };
    }

    componentWillMount() {
        fetchClothingItem(this.props.match.params.postId)
        .then(data => {
        this.setState(state => {
          state.updateClothingItem = data;
          return state;
        });
        console.log("data", data);

        //HERE IT IS RETURNING EXPECTED DATA       

        console.log("this.state.updateClothingItem",this.state.updateClothingItem)    
          })
        .catch(err => {
            console.error("err", err);
        });
    }

    handleSubmit(data) {

        //HERE IT IS THROWING: 

        > "TypeError: Cannot read property 'state' of undefined"

        console.log("this.state.updateClothingItem", this.state.updateClothingItem);
            updateClothingItem(this.state.updateClothingItem.id, data); this.props.router.push("/update");
    }
    render() {
        return (
        <div>
        <FormUpdate
          //onSubmit={this.handleSubmit.bind(this)}
          id={this.state.updateClothingItem.id}
          name={this.state.updateClothingItem.name}
          sleeveLength={this.state.updateClothingItem.sleeveLength}
          fabricWeight={this.state.updateClothingItem.fabricWeight}
          mood={this.state.updateClothingItem.body}
          color={this.state.updateClothingItem.color}
        />
        <button
          type="submit"
          onClick={this.handleSubmit}
          className="addItemButton"
        >
        Button
        </button>
      </div>
    );
  }
}

3 个答案:

答案 0 :(得分:6)

在React代码实现方面,有一些技术上的错误。

首先,使用ES6编写类的方式,需要访问Class属性的任何函数都需要显式binded。在您的情况下,您需要使用arrow functionbinding in constructor绑定handleSubmit函数。

有关详细信息,请参阅此答案:Why and when do we need to bind functions and eventHandlers in React?

其次:您已在componentWillMount函数中设置了异步请求,并且在成功响应中,您正在设置状态。但是,在呈现组件后会在setState中使用componentWillMount,因此您仍需要进行未定义的检查。您应该使用componentDidMount生命周期函数来处理异步请求。

检查此答案是否有 AJAX request in componentDidMount or componentWillMount

第三: setState是异步的,因此在setState函数获胜后记录状态值会导致显示正确的输出。请改用setState callback

有关详细信息,请参阅以下答案:

calling setState doesn't mutate state immediately

When to use React setState callback

代码:

export default class Update extends Component {
    constructor(props) {
        super(props);

        this.state = {
          updateClothingItem: {}
        };
    }

    componentDidMount() {
        fetchClothingItem(this.props.match.params.postId)
        .then(data => {
        this.setState(state => {
          state.updateClothingItem = data;
          return state;
        });
        console.log("data", data);

        //HERE IT IS RETURNING EXPECTED DATA       

        console.log("this.state.updateClothingItem",this.state.updateClothingItem)    
          }) // this statement will not show you correct result since setState is async 
        .catch(err => {
            console.error("err", err);
        });
    }

    handleSubmit = (data) =>  { .    // binding using arrow function here

        console.log("this.state.updateClothingItem", this.state.updateClothingItem);
            updateClothingItem(this.state.updateClothingItem.id, data); this.props.router.push("/update");
    }
    render() {
        return (
        <div>
        <FormUpdate
          //onSubmit={this.handleSubmit.bind(this)}
          id={this.state.updateClothingItem.id}
          name={this.state.updateClothingItem.name}
          sleeveLength={this.state.updateClothingItem.sleeveLength}
          fabricWeight={this.state.updateClothingItem.fabricWeight}
          mood={this.state.updateClothingItem.body}
          color={this.state.updateClothingItem.color}
        />
        <button
          type="submit"
          onClick={this.handleSubmit}
          className="addItemButton"
        >
        Button
        </button>
      </div>
    );
  }
}

答案 1 :(得分:1)

您忘了将handleSubmit功能绑定到课堂上。您可以使用箭头功能来定义函数。

handleSubmit=(data) =>{
...
}

或者您可以在构造函数中绑定该函数。

constructor(props) {
        super(props);
        this.state = {
          updateClothingItem: {}
        };
        this.handleSubmit= this.handleSubmit.bind(this,data);
    }

答案 2 :(得分:0)

构造函数中还没有状态

如果要在构造函数中设置状态,可以这样做

class SomeComponent extends Component {
   constructor(props){
      super(props)

      this.state = { ... }
   }
}

甚至是这样

class SomeComponent extends Component {

   state = {  }

}

但在这种情况下,应正确配置babel