javascript - componentDidMount 或 componentWillMount 我需要使用哪一个

标签 javascript html css reactjs redux

我使用 React 创建了一个类似于 twitter 的框。我在查看 React 文档时发现了几个组件生命周期,但不确定应该使用哪个来提高代码性能:componentDidMount 还是 componentWillMount

当我在文本框中键入内容时,我会在控制台中看到打印文本框值的更新。谁能帮助我了解在这种情况下应该使用哪种方法以及何时使用?

https://jsfiddle.net/c9zv7yf5/2/

class TwitterBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = { enteredTextBoxvalue : '' };
      this.handleChange = this.handleChange.bind(this);

  }

  handleChange(event) {
    this.setState({enteredTextBoxvalue: event.target.value});   

    if((event.target.value).length > 3) {

      this.setState({className : 'wholeContainer'});
      //console.log("long characters");
    }
  }

  render() {
      return (<div>Hello {this.props.name}
              <textarea className={this.state.className}
                value={this.state.enteredTextBoxvalue}
                onChange = {this.handleChange}>
                there should be only 140 characters
            </textarea>
      </div>);
  }
}

ReactDOM.render(
  <TwitterBox name="World" />,
  document.getElementById('container')
);

最佳答案

componentWillMount 在组件渲染之前调用。 组件渲染后立即调用 componentDidMount。

如果您需要准备数据,您可以使用 componentWillMount。 componentDidMount 广泛用于在组件呈现后立即发送 api 调用或抓取数据,强烈建议使用它。

关于javascript - componentDidMount 或 componentWillMount 我需要使用哪一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44233583/

相关文章:

javascript - 如何创建响应式导航栏?

javascript - 为什么我的 JavaScript 中的 "keypress"在单击 HTML 按钮后同时表现得像 "keypress"和 "keyup"?

css - 移动设备的媒体查询不起作用

javascript - 在 D3 径向树中自定义 SVG 文本

javascript - 显示一个隐藏的元素 jquery

Javascript确认表单提交不取消

javascript - SVG:通过 jQuery 更新在 FF 中有效,但在 Safari 中无效,有什么想法吗?

html - Windows Phone Internet Explorer 在一个 td 中放大文本

javascript - 使用 vue.js 和 js 获取数组

javascript - 如何在 javascript 中更新 HTML 正文参数?