React - 无法读取未定义的 属性 'setState'

React - Cannot read property 'setState' of undefined

我正在尝试使用 this.setState() 命令在 PostData 函数中使用字符串值设置状态“错误,如下所示,但在调试时我看到 'this' 未定义,因此 setState没有将字符串分配给 state 中的错误变量。它就像 this 在 Postdata 函数中丢失范围。

我在 Whosebug 上看到了类似的问题,其中通过正确绑定应用 setState 的函数解决了问题,这不是我的情况,因为函数注册已绑定。

class Signup extends Component {

    constructor(props) {
        super(props);

        this.state = {
            username: '',
            password: '',
            confirmPassword: '',
            email: '',
            name: '',
            error: '',
            redirectToReferrer: false
        };

        this.signup = this.signup.bind(this)
        this.onChange = this.onChange.bind(this)
    }


    signup() {
        PostData('signup', this.state).then((result) => {
            let responseJson = result
            console.log(responseJson.message)
            if (responseJson.message.indexOf("registration success") > -1) {
                sessionStorage.setItem('userData', JSON.stringify(responseJson))
                this.setState({ redirectToReferrer: true });
            } else {
                let string = responseJson.message[0]
                this.setState({ error: string })
            }

        });
    }


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

    render() {
        if (this.state.redirectToReferrer || sessionStorage.getItem('userData')) {
            return (<Redirect to={'/home'} />)
        }



        return (

            <div className="row " id="Body">
                <div className="medium-5 columns left">
                    <h4>Signup</h4>
                    <label>Email</label>
                    <input type="text" name="email" placeholder="Email" onChange={this.onChange} />
                    <label>Name</label>
                    <input type="text" name="name" placeholder="Name" onChange={this.onChange} />
                    <label>Username</label>
                    <input type="text" name="username" placeholder="Username" onChange={this.onChange} />
                    <label>Password</label>
                    <input type="password" name="password" placeholder="Password" onChange={this.onChange} />
                    <label>Confirm Password</label>
                    <input type="password" name="confirmPassword" placeholder="Confirm Password" onChange={this.onChange} />

                    <input type="submit" className="button" value="Sign Up" onClick={this.signup} />
                    <a href="/login">Login</a>
                    <input name="error" onChange={this.onChange}></input>
                </div>

            </div>
        );
    }
}

export default Signup

这可能与您的职能范围有关。你的 this.setState 被另一个箭头函数包裹着。您可以将 setState 包装在另一个函数中,但将 class 放入顶层。

您能否尝试为您的 onClick 事件添加一个箭头函数。