Javascript 为什么我不能';无法访问getDerivedStateFromProps()中的静态属性
我是新手,只是关于getDerivedStateFromProps生命周期方法中访问静态属性的问题,下面是我的代码:Javascript 为什么我不能';无法访问getDerivedStateFromProps()中的静态属性,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我是新手,只是关于getDerivedStateFromProps生命周期方法中访问静态属性的问题,下面是我的代码: export default Child extends Component { static counter = 0 ... static getDerivedStateFromProps(props, state) { if(counter = 1) { ... } a += 1; } render() {
export default Child extends Component {
static counter = 0
...
static getDerivedStateFromProps(props, state) {
if(counter = 1) {
...
}
a += 1;
}
render() {
...
}
}
错误是
未定义“计数器”无未定义
您应该使用
类名
来访问它
Child.counter
例如
class Child extends Component {
static counter = 0;
static getDerivedStateFromProps(props, state) {
//"this" is undefined here
console.log("this === " + this);
if(Child.counter === 0) {
console.log("counter is ", Child.counter);
}
return null;
}
render() {
return "Hello"
}
}
您可以尝试下面的SO代码段来查看控制台日志
const{render}=ReactDOM
子类扩展了React.Component{
静态计数器=-123;
静态getDerivedStateFromProps(props,状态){
//这里没有定义
log(“this==”+this);
console.log(“counter is”,Child.counter);
返回null;
}
render(){
回复“你好”
}
}
render(,document.getElementById('root'))代码>
如果(this.counter==1)
。建议按输入错误关闭。@谢谢您的输入。删除了stackblitz链接,并添加了一个SO React片段。