React清除状态onClick

4
我希望在 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

我有一个按钮在另一个组件中,当点击它时设置props,然后我的输入框使用这个作为值。当改变值时,状态更新正常工作。但是,当我点击更新按钮时,数据被正确更新,但状态没有更新。


firebaseCon.content.update 函数内执行了哪些操作? - Carloluis
1个回答

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

那真的起作用了。旧值闪烁,然后字段被清除了,呵呵:P - MartinDK81
太棒了。如果有帮助,请勾选答案:D - Dream_Cap
是啊,我就是忍不住想知道是否有更好的解决方案。这个方法可以用,但旧值仍会短暂闪烁,我觉得非常奇怪。 - MartinDK81
好的,我给了你一个解决方案。因此,我认为这个答案应该被选中,因为没有其他人给出答案。 - Dream_Cap

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接