代码之家  ›  专栏  ›  技术社区  ›  MartinDK81

单击后反应清除状态

  •  4
  • MartinDK81  · 技术社区  · 7 年前

    我想在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

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dream_Cap    7 年前

    尝试将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));