我正在研究变更检测机制,在Reactjs案例中遇到了一些麻烦。
当在react组件中更改props时,将“重新渲染”该组件(由于diff算法,因此并非完全正确,但是这里的想法就在这里)。
我知道,当发生 某种 情况时,请反应浏览其内部虚拟DOM以检查新值是否与前一个相同,然后根据需要重新渲染其真实组件树。
我的问题是:这是 什么东西 。
例如,使用angular 2,我们可以使用zone.js来捕获 异步内容(单击按钮,setTimeout等…) 并触发更改检测。
但是到目前为止,我完全不知道它是由reactjs触发的。
你能帮助我吗 ?
尝试想象这里有两件事:
您需要调用this.setState(),这将更新当前组件 内部 的状态,并随后触发此组件的更新(自动调用render())
这将触发该组件的props / newProps进行更新,随后通过在组件内部调用this.setState()来更新组件(componentWillReceiveProps是React的生命周期方法)
class MyComponent extends React.Component { // initially how the state is set to MyComponent constructor(props) { super(props); this.state = {name: this.props.name}; } // own method to be called inside MyComponent updateName(e) { const newName = e.target.value; if (this.state.name !== newName) { this.setState({name:newName}); } } // changes from the outside componentWillReceiveProps(nextProps) { const newName = nextProps.name; if (this.state.name !== newName) { this.setState({name:newName}); } } render() { return( <div> {this.state.name} <input type="text" onChange={this.updateName.bind(this)} value={this.state.name} /> </div> ) } }
值得指出的是,this.setState()会自动触发render(),而this.state.name =’Bob’不会触发render()。