gpt4 book ai didi

javascript - 为什么 setState 中不带参数的函数调用要在 setState 之前调用?

转载 作者:行者123 更新时间:2023-11-28 17:02:29 31 4
gpt4 key购买 nike

正如 another question 中向我指出的那样,如果我在 setStaterandomQuoteIndex() 中有一个不带参数的函数调用,并且该函数使用该 setState 中设置的状态,那么它是在setState之前调用。

  componentDidMount() {
fetch('https://gist.githubusercontent.com/nataliecardot/0ca0878d2f0c4210e2ed87a5f6947ec7/raw/1802a693d02ea086817e46a42413c0df4c077e3b/quotes.json')
.then(response => response.json())
.then(quotes => this.setState({
quotes,
randomQuoteIndex: this.randomQuoteIndex(),
isDoneFetching: true
}));
}

randomQuoteIndex() {
return random(0, this.state.quotes.length - 1);
}

这会导致错误,因为 quotes 的状态在 randomQuoteIndex() 调用时不可用。

但是,如果我将 randomQuoteIndex() 更改为使用传入的 quotes 参数,如下所示,它就会起作用。

componentDidMount() {
fetch('https://gist.githubusercontent.com/nataliecardot/0ca0878d2f0c4210e2ed87a5f6947ec7/raw/1802a693d02ea086817e46a42413c0df4c077e3b/quotes.json')
.then(response => response.json())
.then(quotes => this.setState({
quotes,
randomQuoteIndex: this.randomQuoteIndex(quotes),
isDoneFetching: true
}));
}

randomQuoteIndex(quotes) {
return random(0, quotes.length - 1);
}

这不是我所期望的;我假设 quotes 的状态在调用 randomQuoteIndex() 时可用,因为它是在 setState 中调用的。为什么在 setState 之前调用 randomQuoteIndex(),即使它位于其中?

最佳答案

这是因为setState是一个异步操作。您仍然可以通过使用 setState 作为回调来使用原始函数

componentDidMount() {
fetch('https://gist.githubusercontent.com/nataliecardot/0ca0878d2f0c4210e2ed87a5f6947ec7/raw/1802a693d02ea086817e46a42413c0df4c077e3b/quotes.json')
.then(response => response.json())
.then(quotes => this.setState({
quotes,
isDoneFetching: true
}, () => {
this.setState({
randomQuoteIndex: this.randomQuoteIndex(),
}); //this callback will be executed after your state is updated.
}));

}

randomQuoteIndex() {
return random(0, this.state.quotes.length - 1);
}

因此,本质上,一旦执行 setState 函数,更新的值只会在更新生命周期完成后反射(reflect),这意味着您可以在 componentDidUpdate 中获取值方法或使用 setState 函数作为回调。

我不推荐此解决方案,但在这种情况下,函数 randomQuoteIndex() 将获取更新的状态值,而无需传递任何参数。

关于javascript - 为什么 setState 中不带参数的函数调用要在 setState 之前调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56956467/

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