我正在关注关于高阶组件(HOC)的 reactjs 教程。我想要一个 HOC 在道具更改时记录道具。
import React, { useState } from 'react';
function logProps(WrappedComponent) {
return class extends React.Component {
componentDidMount() {
console.log("Component was mounted");
}
componentDidUpdate(prevProps) {
console.log("Current props: ", this.props);
console.log("Previous props: ", prevProps);
}
render() {
// Wraps the input component in a container, without mutating it. Good!
return <WrappedComponent {...this.props} />
}
}
}
class CustomDivElement extends React.Component{
render(){
return <div>{this.props.text}</div>
}
}
function App(props) {
const [text, setText] = useState("");
const EnhancedComponent = logProps(CustomDivElement);
return (
<div tabIndex="0" className="App ui container">
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)} />
<EnhancedComponent text={text} />
</div>
)
}
export default App
起初我以为是因为我使用的是 HOC。所以我介绍了另一种生命周期方法,componentDidMount
它正在触发。componentDidUpdate
没有开火,这是为什么呢?