我正在研究更改检测机制,并且在reactjs案例中遇到了一些麻烦。
当反应组件中的 props 发生变化时,该组件将被“重新渲染”(由于 diff 算法的原因,这并不完全正确,但想法就在这里)。
我知道当某物发生这种情况时,React 会浏览其内部虚拟 DOM 以检查新值是否与前一个值相同,并根据需要重新渲染其真实组件树。
我的问题是:这是什么某物.
例如,使用 Angular 2,我们有 zone.js 可以捕获异步内容(按钮单击、setTimeout 等...)并触发变化检测。
但目前,我根本不知道它是由reactjs触发的。
你能帮助我吗 ?
尝试想象这里有两件事:
- 组件(COMPONENT)本身,以及
- 组件外部的事物(OUTSIDE):
COMPONENT 内部的更改
您需要调用 this.setState(),这将更新状态inside当前组件,随后触发该组件的更新(自动调用 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()。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)