getting error: Cannot read property state of undefined

前端 未结 3 2087
生来不讨喜
生来不讨喜 2020-11-28 15:42
import React, { Component } from \"react\";
import FormUpdate from \"../components/formUpdate\";
import { fetchClothingItem, updateClothingItem } from \"../actions/c         


        
3条回答
  •  被撕碎了的回忆
    2020-11-28 16:34

    There are a few things that are technically wrong in terms of React code implementation.

    Firstly, With ES6 style of writing a class, any function that needs to access the Class properties need to be explicitly binded. In your case you need to bind the handleSubmit function using arrow function of or binding in constructor.

    See this answer for more details: Why and when do we need to bind functions and eventHandlers in React?

    Secondly: You have your async request set up in the componentWillMount function and in the success response of it, you are setting state. However using setState in componentWillMount is triggered after the component is rendered so you still need to have an undefined check. You should instead make use of componentDidMount lifecycle function for async requests.

    Check this answer on whether to have AJAX request in componentDidMount or componentWillMount

    Third: setState is asynchronous and hence logging the state values after the setState function won't result in the correct output being displayed. Use the setState callback instead.

    See these answers for more details:

    calling setState doesn't mutate state immediately

    When to use React setState callback

    Code:

    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 (
            
    ); } }

提交回复
热议问题