我使用 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/