【问题标题】:React clear state onClick反应清除状态 onClick
【发布时间】:2018-08-16 19:52:51
【问题描述】:

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

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

【问题讨论】:

  • firebaseCon.content.update 函数内部执行了哪些操作?

标签: reactjs state


【解决方案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
  • 太棒了。如果有帮助,请勾选答案:D
  • 是的,我只是忍不住想是否有更好的解决方案。这可行,但旧值仍然会很快闪烁,我觉得这很奇怪。
  • 好吧,我给了你一个解决方案。所以我认为这个答案值得选择,因为没有其他人给出答案。
猜你喜欢
  • 2017-10-20
  • 2020-11-11
  • 1970-01-01
  • 1970-01-01
  • 2018-12-30
  • 2018-01-18
  • 2020-02-01
  • 2020-04-03
  • 2020-04-21
相关资源
最近更新 更多