Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

reactjs - Cannot read property 'state' of undefined solv

Any help or hint would be greatly appreciated it!!

In the onFormSubmit() I get error: Cannot read property 'state' of undefined. Why does converting the onFormSubmit to an arrow function below solve the problem? In stackoverflow, the url :Cannot read property 'state' of undefined

STATED HOW TO SOLVE THE PROBLEM: As someone already mentioned, you have to bind the method in the constructor or in the onClick as he did

What does bind the method means in simple terms?

   onFormSubmit = event => {
   event.preventDefault();
   console.log(this.state.term);

}

Why does this other way also works:

 <form onSubmit={event => this.onFormSubmit(event)} className="ui form">
            <div className="field">

SearchBar.js

                import React from 'react';

            class SearchBar extends React.Component {

               state = { term: '' };


               onFormSubmit(event) {
                event.preventDefault();
                console.log(this.state.term);
               }


                render() {
                return (
                <div className="ui segment">
                    <form onSubmit={this.onFormSubmit} className="ui form">
                    <div className="field">
                        <label>Image Search</label>
                        <input type="text" value={this.state.term} onChange={(e) => this.setState({ term: e.target.value.toUpperCase()})} />
                    </div>
                    </form>

                </div>);
                }
            }

            export default SearchBar;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What is happening is this is undefined in onFormSubmit function why? because onFormSubmit has not been registered as SearchBar property. to solve either bind (onclick or in the constructor) or change your function into arrow function..... why arrow functions auto binds read about that in here. And also add constructor to your class and call the super() method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...