简体   繁体   中英

setState not a function after binding this

I have a simple form allowing users to create a plain text post. The code below generates a successful server side response following the createPostRequest call. However, following a successful post, I would like to update the state to empty out the postBody field and update the UI to reflect this change, and then allow users to make subsequent requests to post additional messages.

Currently, everything works well for the first request only, and after a successful initial request, the postBody field isn't emptying out and when attempting to change the value of the post field following the first initial request, every key stroke is resulting in the following error:

Uncaught TypeError: Cannot read property 'setState' of undefined

Note, what is a bit odd, is that I am getting the above error despite binding this to the onChange method in the constructor.

Did anyone run into this issue? I appreciate any suggestions on how to resolve.

constructor(props) {
        super(props);

        this.state = {
            postBody : "",
            location: "main"
        };

        this.onSubmit = this.onSubmit.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    onChange(e) {
        this.setState({
            [e.target.name] : e.target.value
        });
    }

    onSubmit(e) {
        e.preventDefault();

        this.props.createPostRequest(this.state).then(
            () => {

                this.setState = ({
                    postBody : ""
                });
            }
        )
    }

    render() {

        return (
            <div className="create-post-inner col-md-12">
                <form id="createPost" onSubmit={ this.onSubmit } >
                    <textarea value={this.state.postBody} className="form-control postInput" name="postBody" onChange={ this.onChange } >
                    </textarea>
                    <span>The value of the state is {this.state.postBody}</span>
                    <input type="submit" className="submit btn btn-primary" />
                </form>
            </div>
        );
    }

there is an extra = after this.setState . Change the following to

 this.props.createPostRequest(this.state).then(
        () => {

            this.setState({
                postBody : ""
            });
        }
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM