gpt4 book ai didi

javascript - ComponentDidMount 之外的状态似乎没有更新

转载 作者:行者123 更新时间:2023-12-04 08:49:04 29 4
gpt4 key购买 nike

你好,当我在 componentDidMount 方法之外的任何地方控制台记录我的组件的状态时,我发现我的状态充满了空数组,而这些空数组本应被构建。我正在从 JSON 文件和 componentDidMount 中获取数据,我可以看到状态更改为包含数据的数组,但是在其他任何地方(例如在我的渲染中),状态都返回到其初始状态。

我想这个问题与组件的生命周期有关,所以很想了解发生了什么。

非常感谢!

import React from 'react';
import * as metrics from './metrics.json';

class MetricsTable extends React.Component {
state = {
coverages: [],
speeds: [],
qualities: [],
responsiveness: [],
securities: []
}

componentDidMount() {
metrics[0].map((metric) => {

if (metric.level_1 === 'Coverage') {
let joined = this.state.coverages.splice(0, 0, metric)
this.setState({ coverages: [...joined] })
}

if (metric.level_1 === 'Speed') {
let joined = this.state.speeds.splice(0, 0, metric)
this.setState({ speeds: [...joined] })
}

if (metric.level_1 === 'Quality') {
let joined = this.state.qualities.splice(0, 0, metric)
this.setState({ qualities: [...joined] })
}

if (metric.level_1 === 'Responsiveness') {
let joined = this.state.responsiveness.splice(0, 0, metric)
this.setState({ responsiveness: [...joined] })
}

if (metric.level_1 === 'Security') {
let joined = this.state.securities.splice(0, 0, metric)
this.setState({ securities: [...joined] })
}
})
}

render() {
// when I console log on this line I get empty arrays for my state
return (
<div>
// this following line displays my state with empty arrays
<pre>{JSON.stringify(this.state)}</pre>
hello
</div>
);

}

}

export default MetricsTable;

第一张图片显示了包含数据数组的状态,这张是在 componentDidMount 中登录的控制台。

第二张图是我render函数中this.state的console log enter image description here

this is the console log in my render function

最佳答案

问题与这种代码有关:

let joined = this.state.coverages.splice(0, 0, metric)

请注意,joined 始终是一个空数组。 splice 方法不返回新的结果数组。

您可以像这样更新代码:

let joined = [...this.state.coverages, metric];

关于javascript - ComponentDidMount 之外的状态似乎没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64170005/

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