gpt4 book ai didi

javascript - 为什么我无法访问 getDerivedStateFromProps() 中的静态属性

转载 作者:行者123 更新时间:2023-11-30 19:09:59 24 4
gpt4 key购买 nike

我是 React 的新手,只是一个关于在 getDerivedStateFromProps 生命周期方法中访问静态属性的问题,下面是我的代码:

export default Child extends Component {
static counter = 0
...
static getDerivedStateFromProps(props, state) {
if(counter = 1) {
...
}
a += 1;
}

render() {
...
}
}

错误是

'counter' is not defined no-undef

最佳答案

你应该使用类名来访问它..

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 是静态方法,因此它无法访问组件实例。

以下文章可能有助于了解何时使用它。

https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#when-to-use-derived-state

关于javascript - 为什么我无法访问 getDerivedStateFromProps() 中的静态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58593280/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com