绑定 this 后 setState 不是函数

IT技术 javascript reactjs
2021-05-12 01:27:03

我有一个简单的表单,允许用户创建纯文本帖子。下面的代码在createPostRequest调用后生成成功的服务器端响应但是,在成功发布后,我想更新状态以清空 postBody 字段并更新 UI 以反映此更改,然后允许用户发出后续请求以发布其他消息。

目前,一切都只适用于第一个请求,并且在成功的初始请求之后,postBody 字段不会清空,并且在第一个初始请求之后尝试更改 post 字段的值时,每次击键都会导致以下错误:

Uncaught TypeError: Cannot read property 'setState' of undefined

请注意,有点奇怪的是,尽管绑定this到构造函数中的 onChange 方法,但我还是收到了上述错误

有没有人遇到过这个问题?我感谢任何有关如何解决的建议。

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>
        );
    }
1个回答

=在 this.setState 之后还有一个额外的将以下内容更改为

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

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