反应清除状态onClick

时间:2018-03-08 12:46:10

标签: reactjs state

我希望在onClick被解雇后清除我的状态。但是,我的状态不会更新,而是呈现初始状态。

这是代码

import React from 'react';
import {firebaseCon} from '../connection';

class Update extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
			title: ""
        };

        this.updateItem = this.updateItem.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }

    componentWillReceiveProps(props) {
        this.setState({
            title: props.item.title
        });
    }

    updateItem(itemId) {
        let inputVal = document.getElementById("editData").value;
        firebaseCon.content.update('text', itemId, { title: inputVal })
        .then(() => console.log('Updating the entry succeeded'))
        .catch((e) => console.error(e));
        this.setState({ title: "" });
    }

    handleChange(e) {
        var value = e.target.value;
        this.setState({ title: value });
    }

    render() {
        return (
            <div className="input-field col s12">
                <i className="material-icons prefix">mode_edit</i>
                <input type="text" id="editData" value={this.state.title || ""} onChange={this.handleChange} />
                <button className="waves-effect waves-light btn" onClick={this.updateItem.bind(this, this.props.item.id)}>UPDATE</button>
            </div>
        )
    }
}

export default Update

我在另一个组件中有一个按钮,在单击时设置道具,然后我的输入字段将其用作值。更改值时,状态更新,这正常工作。但是,当我单击我的更新按钮时,数据已正确更新,但状态未更新。

1 个答案:

答案 0 :(得分:1)

尝试将setState放入then块中。 then块可能会被调用,然后由于异步而永远不会到达setState。

尝试将setState放在then块中,如下所示:

then(() => {
  console.log('Updating the entry succeeded');
  this.setState({title: ""}); // <--- goes inside the then block, so it gets executed 

}).catch((e) => console.error(e));
相关问题