我是React和編程的新手,對於componentWillReceiveProps
方法有疑問。在LikesComponent
類裏面有updateLikes
方法ReactDOM.render(<LikesComponent likes={this.props.likes+1} />, document.getElementById("app"))
。我認爲每次調用<ComponentName />
都會創建一個新實例,這就是爲什麼當我看到componentWillReceiveProps
方法記錄的消息時我非常驚訝。相反,我期待看到由getDefaultProps, getInitialState and render
方法記錄的消息。那麼,不打電話<ComponentName />
總是創建該類的新實例?您能否詳細說明何時創建新實例以及何時更新實例?我現在很困惑。提前致謝。React - componentWillReceiveProps方法:新vs更新實例
body {
padding: 40px;
font-family: "helvetica neue", sans-serif;
}
.container {
width: 600px;
margin: auto;
color: black;
padding: 20px;
text-align: center;
}
.container h1 {
margin: 0;
padding: 20px;
font-size: 36px;
}
.container .btn {
border: 0;
padding: 15px;
margin: 10px;
width: 20%;
font-size: 15px;
outline: none;
border-radius: 3px;
color: #FFF;
font-weight: bold;
}
.btn.blue-btn {
background-color: #55acee;
box-shadow: 0px 5px 0px 0px #3C93D5;
}
.btn.blue-btn:hover {
background-color: #6FC6FF;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React tutorial</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
var LikesComponent = React.createClass({
updateLikes: function() {
ReactDOM.render(
<LikesComponent likes={this.props.likes+1}/>,
document.getElementById("app")
)
},
getDefaultProps: function() {
console.log("getDefaultProps");
return({
likes: 0
})
},
getInitialState: function() {
console.log("getInitialState");
return({
popular: false
})
},
componentWillReceiveProps: function(nextProps) {
console.log(nextProps);
console.log("Componentwillreceiveprops");
this.setState({
popular: nextProps.likes >= 10
})
},
render: function() {
console.log("Component Rendered");
return (
<div className="container">
<h1>{this.state.popular ? "I'm popular" : null}</h1>
<button className="btn blue-btn" onClick={this.updateLikes}>Likes: {this.props.likes}</button>
</div>
)
}
});
ReactDOM.render(
<LikesComponent />,
document.getElementById("app")
);
</script>
</body>
</html>