Я хочу, чтобы консоль super
в моем InheritComponent
constructor
метод. Но в хром-консоли он бросает ошибку. Зачем?Почему console.log (super) в конструкторе React Component выдает ошибку?
class BaseComponent extends React.Component{
static defaultProps = {
title: 'Learn React By Examples'
}
constructor(props) {
console.log(props);
super(props);
}
setTitle(title) {
document.title = title || this.props.title;
return document.title;
}
}
class InheritComponent extends BaseComponent{
state = {
title: ''
};
constructor(props) {
super(props);
//here throw an Error. Why? I want to console.log `super`
console.log(super);
}
componentDidMount() {
const title = this.setTitle('组件继承')
this.setState({title});
}
render() {
return <div>
<p>I inherit BaseComponent</p>
<p>current title is {this.state.title}</p>
</div>
}
}
ReactDOM.render(
<InheritComponent />,
document.body
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Выше мой демонстрационный код.
Я думаю, что вы не можете добавить что-либо перед вызовом super, можете ли вы удалить инструкцию console.log и попробовать один раз? –
@HarkiratSaluja удалить инструкцию console.log будет работать. Но я хочу утешить «супер». И, моя инструкция console.log после 'super (props)' statement – novaline