reactjs - 什么时候使用 'componentDidUpdate'方法?

标签 reactjs

我写了几十个Reactjs文件,但我从未使用过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).

关于reactjs - 什么时候使用 'componentDidUpdate'方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38759703/

相关文章:

reactjs - React Router 重定向到登录页面但不渲染登录组件

reactjs - 大量输入后 TextInput 变慢 React-native

reactjs - 如何在 react 中的 &lt;input&gt; 下附加验证错误消息?

reactjs - React Router 用户角色的最佳实践 (Firebase)

javascript - 运行 Electron 时不渲染JSX组件

javascript - 使用 redux 表单添加和编辑多个主题

reactjs - react-scroll在Electron应用程序中不起作用

reactjs - 无法将文本对齐应用于 Material UI 输入组件,但其他一切正常

javascript - Redux 状态更改后 React 容器不会重新渲染

reactjs - React 中的 shouldComponentUpdate 和 componentWillUpdate 有什么区别?