gpt4 book ai didi

javascript - 为什么我需要在 componentDidUpdate() 中使用 prevProps 和 prevState ?

转载 作者:行者123 更新时间:2023-12-03 13:39:56 25 4
gpt4 key购买 nike

我构建了一个简单的计数器应用程序:

class Counter extends React.Component {

constructor(props) {
super(props);
this.handleAddOne = this.handleAddOne.bind(this);
this.handleMinusOne = this.handleMinusOne.bind(this);
this.handleReset = this.handleReset.bind(this);
this.state = {
count: 0
};
}

componentDidMount() {
const stringCount = localStorage.getItem('count');
const count = parseInt(stringCount);

if (isNaN(count) === false) {
this.setState(() => ({ count }));
}
}

componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
localStorage.setItem('count', this.state.count);
console.log('componentDidUpdate');
}
}

handleAddOne() {
this.setState((prevState) => {
return {
count: prevState.count + 1
}
});
}

handleMinusOne() {
console.log('handleMinusOne');
this.setState((prevState) => {
return {
count: prevState.count - 1
}
});
}

handleReset() {
this.setState(() => {
return {
count: 0
}
});
}

render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.handleAddOne}>+</button>
<button onClick={this.handleMinusOne}>-1</button>
<button onClick={this.handleReset}>reset</button>
</div>
);
}
}

ReactDOM.render(<Counter />, document.getElementById('app'));

我的问题是关于componentDidUpdate()。在其中,我检查 prevState.count 是否与 this.state.count 不同。如果不相同,则将 localStorage 设置为新计数。如果相同,我什么也不做。

在当前的 componentDidUpdate() 中,我需要 prevProps 作为该函数正常工作的参数。例如,如果我只有这个:

componentDidUpdate(prevState) {
if (prevState.count !== this.state.count) {
localStorage.setItem('count', this.state.count);
console.log('componentDidUpdate');
}
}

然后,每次重复按下重置按钮时,组件都会设置 localStorage,即使计数仍为 0。

这是怎么回事?如果我从未在该函数中使用过 props,为什么我需要 prevProps 才能让 componentDidUpdate() 正常工作?

最佳答案

componentDidUpdate 中的第一个参数是 prevProps。第二个参数是 prevStateThe documentation明确指出:

componentDidUpdate(prevProps, prevState, snapshot)

这个

componentDidUpdate(prevState) {...}

不是钩子(Hook)的正确签名。尽管第一个参数名为 prevState,但它包含以前的 props。

可以根据函数参数的数量来替换函数参数,但这在 React 中没有实现,并且通常被认为是一种不好的做法,因为这会导致更复杂的签名。

为了不引起 linter 警告,未使用的参数可以按照约定加下划线:

componentDidUpdate(_prevProps, prevState) {...}

关于javascript - 为什么我需要在 componentDidUpdate() 中使用 prevProps 和 prevState ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53734007/

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