简体   繁体   English

状态在ReactJS中无法正常工作

[英]State not working properly in ReactJS

What I'm trying to do is, store a input field value to a state and then, If a user click on save button or store button then input field will be vanished so editing will be false.I'm trying to check the state length when user click on the save button. 我想做的是,将输入字段的值存储为一个状态,然后,如果用户单击“保存”按钮或“存储”按钮,则输入字段将消失,因此编辑将为false。我正在尝试检查状态用户单击保存按钮时的长度。 The problem is there. 问题就在那里。 it's say's this error: Uncaught TypeError: Cannot read property 'state' of null , But I've already stored data on editData state why is that please can you tell me? 就是说这是一个错误: Uncaught TypeError: Cannot read property 'state' of null ,但是我已经将数据存储在editData state上了,那为什么你能告诉我?

Here is Codes to understand better 这是更好理解的代码

class EditData extends Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.state = {
            editData: ''
        }
    }
    handleChange(e) {
        this.setState({editData: e.target.value})
    }

    save() {
        if (this.state.editData.length !== 0) {
            this.setState({isEditing: false});
            console.log(this.state.editData + 'Added on your database')
        } else {
            alert('Hahah Are you')
        }
        // console.log(this.refs.valTo.value);
    }
    render() {
        return (
            <div>
                <input onChange={this.handleChange} type="text" defaultValue={this.props.data}  /> <button onClick={this.save}>Save</button> <button>cancel</button>
            </div>
            );
    }
}

You need to bind handleChange and save . 您需要绑定handleChangesave Check also that you initialized state in the constructor. 还要检查您是否在构造函数中初始化了state

In the constructor do: 在构造函数中执行以下操作:

this.handleChange = this.handleChange.bind(this);
this.save= this.save.bind(this);
this.state = {};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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