加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

reactjs – 何时使用React“componentDidUpdate”方法?

发布时间:2020-12-15 20:55:41 所属栏目:百科 来源:网络整理
导读:我写了几十个React文件,从不使用componentDidUpdate方法。 是否有任何关于何时需要使用此方法的典型示例? 我想要一些真实的例子,而不是简单的演示。 谢谢你的回答! 一个简单的例子是一个应用程序,它从用户收集输入数据,然后使用Ajax将所述数据上传到数
我写了几十个React文件,从不使用componentDidUpdate方法。

是否有任何关于何时需要使用此方法的典型示例?

我想要一些真实的例子,而不是简单的演示。

谢谢你的回答!

一个简单的例子是一个应用程序,它从用户收集输入数据,然后使用Ajax将所述数据上传到数据库。这是一个简化的例子(没有运行它 – 可能有语法错误):
export default class Task extends React.Component {

  constructor(props,context) {
    super(props,context);
    this.state = {
      name: "",age: "",country: ""
    };
  }

  componentDidUpdate() {
    this._commitAutoSave();
  }

  _changeName = (e) => {
    this.setState({name: e.target.value});
  }

  _changeAge = (e) => {
    this.setState({age: e.target.value});
  }

  _changeCountry = (e) => {
    this.setState({country: e.target.value});
  }

  _commitAutoSave = () => {
    Ajax.postJSON('/someAPI/json/autosave',{
      name: this.state.name,age: this.state.age,country: this.state.country
    });
  }

  render() {
    let {name,age,country} = this.state;
    return (
      <form>
        <input type="text" value={name} onChange={this._changeName} />
        <input type="text" value={age} onChange={this._changeAge} />
        <input type="text" value={country} onChange={this._changeCountry} />
      </form>
    );
  }
}

因此,只要组件发生状态更改,它就会自动保存数据。还有其他方法可以实现它。在更新DOM并清空更新队列后需要执行操作时,componentDidUpdate特别有用。它可能对复杂渲染和状态或DOM更改最有用,或者当您需要某些东西成为最后要执行的东西时。

上面的例子虽然相当简单,但可能证明了这一点。改进可以是限制自动保存可以执行的次数(例如,每10秒最多),因为现在它将在每个按键行程上运行。

我在这个fiddle上做了一个演示来演示。

有关更多信息,请参阅official docs

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读