我是React的新手,只是一个关于getDerivedStateFromProps生命周期方法中访问静态属性的问题,下面是我的代码:
export default Child extends Component {
static counter = 0
...
static getDerivedStateFromProps(props, state) {
if(counter = 1) {
...
}
a += 1;
}
render() {
...
}
}
错误是
未定义“计数器” no-undef
答案 0 :(得分:1)
您应该使用class name
进行访问。
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
class Child extends React.Component {
static counter = -123;
static getDerivedStateFromProps(props, state) {
//this is undefined here
console.log("this === " + this);
console.log("counter is ", Child.counter);
return null;
}
render() {
return "Hello"
}
}
render(<Child />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
还请注意,由于getDerivedStateFromProps
是静态方法,因此它无权访问组件实例。
以下文章可能会帮助您何时使用它。