React-无法读取未定义的属性'setState' [英] React- Cannot read property 'setState' of undefined

查看:665
本文介绍了React-无法读取未定义的属性'setState'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  import __fetch fromisomorphic-fetch; 
导入从反应中反应;
从react-inline-css导入InlineCss;
import从react-transmit传输;

从'./components/header'导入标题

类注册扩展React.Component {

componentWillMount(){
if (__SERVER__){
console.log(来自注册的Hello服务器);


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



构造函数(){
super()

this.state = {
name:'' ,
密码:''
}

//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。名称});
}

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


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


$ b $提交(){
console.log(this)
console.log(this.state)
if( this.emtinessChecker()){
alert(请不要留下任何空白!);
}
else {
var xhr = new XMLHttpRequest(); //新的HttpRequest实例
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(){

//让(用户名,密码)= 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>
注册
< / div>


< ul className =account-fields>

< div className ='Name'>
< label>用户名< / label>
< input type =textvalue = {this.state.name } onChange = {this.onChangeName} />
< / div>

< div className ='密码'>
< label>密码< / label> ;
< input type =passwordvalue = {this.state.password} onChange = {this.onChangePassword} />
< / div>


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

< / ul>
< / div>

< / InlineCss>




);
}
/ **
*< InlineCss>组件允许您为组件编写CSS样式表。以`&`为目标
*您的组件,并使用`& selectors`。请明确点。
* /
static css(){
return(`
& .Register {
position:fixed;
right:550px;
底部:550px;
字体大小:50px;
}
& .account-fields {
位置:固定;
右:550px;
底部:450px;
font-size:20px;
}
& .submitForm {
位置:固定;
右:10px;
底部: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;
}
`);
}

}

导出默认Transmit.createContainer(注册);


解决方案

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

<$ p $ 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。密码});
}

通过使用 property:

  onChangeName(e){
this.setState({name:目标价值});


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

您还需要确保 this




如果你的输入是合适的 name 道具,您用一个 onChange 处理程序替换它们:

 构造函数(道具){
super(道具)
// ...
this.onChange = this.onChange.bind(this)


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

render(){
// ...
< input type =textname =namevalue = {this.state.name} onChange = {this.onChange} />
< input type =passwordname =passwordvalue = {this.state.password} onChange = {this.onChange} />
// ...
}


for some reason, I'm getting the error " React- Cannot read property 'setState' of undefined". So this.state is never getting updated with the values that the user inputs. When I tried the binding that is commented out, I get strange behavior where I'm unable to type input for the username and I no longer get the null error, but the values are just undefined. Any help would be appreciated. Thanks.

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);

解决方案

In these event handlers, e.target is the <input> which triggered the event.

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 });
}

You get an input's value by using its value property:

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

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

You also need to ensure this is bound properly, as per the commented-out code in your constructor.


If you give your inputs suitable name props, you replace these with a single onChange handler:

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}/>
  // ...
}

这篇关于React-无法读取未定义的属性'setState'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆