React-无法读取undefined的属性'setState'

时间:2015-11-29 22:02:34

标签: javascript html forms reactjs this

由于某种原因,我收到错误“React-无法读取未定义的属性'setState'”。因此,this.state永远不会使用用户输入的值进行更新。当我尝试注释掉的绑定时,我得到了奇怪的行为,我无法输入用户名的输入,我不再得到null错误,但值只是未定义。任何帮助,将不胜感激。感谢。

import __fetch from "isomorphic-fetch";
import React from "react";
import InlineCss from "react-inline-css";
import Transmit from "react-transmit";

import Header from './components/header'

class Registration extends React.Component {

    componentWillMount () {
        if (__SERVER__) {
            console.log("Hello server from Registration");
        }

        if (__CLIENT__) {
            console.log("Hello Registration screen");
        }
    }

    constructor () {
        super()

        this.state = {
            name: '',
            password: ''
        }

         //this.onChangeName = this.onChangeName.bind(this);
         //this.onChangePassword = this.onChangePassword.bind(this);
    }

    onChangeName(e) {
        //this.state.name = e.target.name
        this.setState({ name: e.target.name});
    }

    onChangePassword(e) {
        //this.state.password = e.target.name
        this.setState({ password: e.target.password });
    }


    emptinessChecker(){
        let {name, password} = this.state
        console.log(name)
        if (name === "" || password === "") {
            return true;
        }
        else {
            return false;
        }
    }

    submit() {
        console.log(this)
        console.log(this.state)
        if (this.emptinessChecker()){
            alert("Please do not leave any fields blank!");
        }
        else{
            var xhr = new XMLHttpRequest();   // new HttpRequest instance 
            xhr.open("POST", "/edit");
            xhr.addEventListener("load", e => {
                console.log(xhr.responseText)
            });

            xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
            xhr.send(JSON.stringify(this.state));
            window.location.href= "/success"
        }
    }


    render () {

        //let {username, password} = this.state

        if (__SERVER__) {
            console.log("render server from registration");
        }
        if (__CLIENT__) {
            console.log('we client now!')
        }

        return (
            <InlineCss stylesheet={Registration.css()} namespace="Registration">
                <Header />



                <div>
                    <div className = "Register" >
                        Register
                    </div>


                    <ul className="account-fields">

                        <div className = 'Name'>
                                <label>Username</label>
                                <input type="text" value={this.state.name} onChange={this.onChangeName} />
                        </div>

                        <div className = 'Password'>
                                <label>Password</label>
                                <input type="password" value={this.state.password} onChange={this.onChangePassword} />
                        </div>


                        <div className='submitForm'>
                            <div className='submit' onClick={e=>this.submit()}>Submit</div>
                        </div>

                    </ul>
                </div>

            </InlineCss>




        );
    }
    /**
     * <InlineCss> component allows you to write a CSS stylesheet for your component. Target
     * your component with `&` and its children with `& selectors`. Be specific.
     */
    static css () {
        return (`
            & .Register {
                position: fixed;
                right: 550px;
                bottom: 550px;
                font-size: 50px;
            }
            & .account-fields {
                position: fixed;
                right: 550px;
                bottom: 450px;
                font-size: 20px;
            }
            & .submitForm {
                position: fixed;
                right: 10px;
                bottom: 10px;
                width: 200px;
            }
            & .submit {
                cursor: pointer;
                text-align: center;
                font-size: 20px;
                padding: 10px;
                background-color: #00E4A5;
                color: #fff;
                border-radius: 5px;
                box-shadow: 0 2px 10px 0 rgba(0,0,0,.13);
                border-bottom: 2px solid #00C791;
                text-shadow: 0px -1px 0px #009E73;
            }
        `);
    }

}

export default Transmit.createContainer(Registration);

3 个答案:

答案 0 :(得分:13)

在这些事件处理程序中,e.target是触发事件的<input>

onChangeName(e) {
    //this.state.name = e.target.name
    this.setState({ name: e.target.name});
}

onChangePassword(e) {
    //this.state.password = e.target.name
    this.setState({ password: e.target.password });
}

您可以使用其value属性获取输入值:

onChangeName(e) {
    this.setState({name: e.target.value});
}

onChangePassword(e) {
    this.setState({password: e.target.value});
}

根据构造函数中已注释掉的代码,您还需要确保this绑定正确。

如果您为输入提供了合适的name道具,则可以使用单个onChange处理程序替换它们:

constructor(props) {
  super(props)
  // ...
  this.onChange = this.onChange.bind(this)
}

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

render() {
  // ...
  <input type="text" name="name" value={this.state.name} onChange={this.onChange}/>
  <input type="password" name="password" value={this.state.password} onChange={this.onChange}/>
  // ...
}

答案 1 :(得分:5)

修改

如果您要在构造函数中遵循绑定模式,请确保使用正确的构造函数调用:

constructor (props) {
    super(props)

在构造函数中注意props

原始答案

由于您似乎正在使用ES6组件定义,因此您应该在呈现的组件中绑定到this

<input type="text" value={this.state.name} onChange={this.onChangeName.bind(this)} />

您无需在构造函数中定义此内容:

 //this doesn't work
 //this.onChangeName = this.onChangeName.bind(this);
 //this.onChangePassword = this.onChangePassword.bind(this);

看起来也许你在你的例子中遗漏了一些代码,所以我不确定你是否试图摆脱不必要的部分为了示例或什么,但要确保你的组件是结构合理。

答案 2 :(得分:0)

如果使用箭头功能,则无需绑定。

onNameChange = (e)=> {
this.setState({name:e.target.value});
}

onPasswordChange = (e) => {
this.setState({password:e.target.value});
}