【发布时间】:2019-07-09 07:02:38
【问题描述】:
要更新子组件中的props对象,通常使用生命周期方法ComponentWillReceiveProps。但我意识到子组件的props 可以在不监听ComponentWillReceiveProps 的情况下更新。
例如,在下面名为App的组件中,子组件Comp可以在不监听生命周期方法ComponentWillReceiveProps的情况下接收props。
主要的App组件:
import React from 'react';
import ReactDOM from 'react-dom';
import {Comp} from "./comp";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
this.incrementCounter = this.incrementCounter.bind(this);
}
componentDidMount() {
this.setState({
counter: 100
})
}
incrementCounter() {
this.setState({
counter: this.state.counter + 1
})
}
render() {
return (
<div>
<button onClick={this.incrementCounter}>Increment</button>
<br />
<br />
<Comp counter={this.state.counter}/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('container'));
和子Comp组件:
import React from 'react';
export class Comp extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
componentDidUpdate(prevProps, prevState) {
console.log("prev props ", prevProps);
console.log("prev state", prevState)
}
render() {
return <span>Props received: {JSON.stringify(this.props)}</span>
}
}
这也是我准备的上述代码的工作演示
您会看到子组件Comp 接收到属性counter 而不监听任何生命周期方法。
这是什么意思?我错过了什么吗?
【问题讨论】:
-
我认为子组件正在重新渲染。这就是您获得更新道具的原因。当 App 的状态发生变化时,它会再次渲染,使子组件也重新渲染。当不重新渲染父组件时,生命周期方法会派上用场。我们只希望我们的子组件重新渲染。
-
@OsamaKhalid 我不明白。能否举个例子,父组件没有被重新渲染,而子组件被重新渲染。
-
对不起,我在上面的评论中犯了一个错误。 ComponentWillReceiveprops 不控制子组件的重新渲染。当父组件的状态发生变化时,子组件总是会重新渲染。这种方法的用途是让我们为子组件做出逻辑决策,因为它具有先前的 props 和 nextprops,因此我们可以在调用子函数的渲染之前使用它们为子组件设置一些数据/状态.
标签: javascript reactjs application-lifecycle