gpt4 book ai didi

javascript - 如何在构造函数中初始化依赖于另一个方法值的状态方法

转载 作者:行者123 更新时间:2023-12-02 23:33:56 24 4
gpt4 key购买 nike

我试图在构造函数中将三个函数初始化为状态,以便从这些函数中获取值,并在第一次渲染之前使这些值在状态中可用。但是,其中一个函数的变量依赖于前一个函数的值,因此我收到错误。

我该如何解决这个问题?代码如下!

App.js 文件

import React from "react";
import Calendar from "./Calendar"

function App() {
return (
<div>
<Calendar />
</div>

)
}

export default App;

Calendar.js 文件

import React from "react";


class Calendar extends React.Component {
constructor() {
super();

this.state = {
//curLastDate() is dependent on lastDayOfMonth()
lastDayOfMonth: this.storeLastDate(),
currentLastDate: this.curLastDate()
}
}
/*
Stores the last date of all months of the current year
Format: [ ["Thu", "Jan", "31", "2019]... ]
*/
storeLastDate() {
let date,
string,
lastDate,
list = [];

date = new Date();

for (let i = 1; i < 13; i++) {

lastDate = new Date(date.getFullYear(), i, 0);
string = lastDate.toDateString().split(" ");
list.push(string);
}

return list;
}

/*
Finds the matching month of current date
*/
curLastDate() {

for (let i = 0; i < this.state.lastDayOfMonth.length; i++) {
if (this.state.currentDate[1] === this.state.lastDayOfMonth[i][1]) {
console.log(this.state.lastDayOfMonth[i][1]);
return this.state.lastDayOfMonth[i][1];
}
}
}

render() {
return (
null
)
}

}
export default Calendar;

最终,我想将从函数获取的值初始化为 React 第一次渲染之前的状态。感谢您提前的帮助!

最佳答案

在 componentDidMount 中设置值并将回调传递给 .setState()

constructor() {
super();
this.state = {
lastDayOfMonth: [],
currentLastDate: [],
currentDate: new Date(),
};
}

storeLastDate = () => {
let date,
string,
lastDate,
list = [];

date = new Date();

for (let i = 1; i < 13; i++) {
lastDate = new Date(date.getFullYear(), i, 0);
string = lastDate.toDateString().split(' ');
list.push(string);
}

return list;
}

/*
Finds the matching month of current date
*/
curLastDate = () => {
for (let i = 0; i < this.state.lastDayOfMonth.length; i++) {
if (this.state.currentDate[1] === this.state.lastDayOfMonth[i][1]) {
console.log(this.state.lastDayOfMonth[i][1]);
return this.state.lastDayOfMonth[i][1];
}
}
}

componentDidMount = () => {

const lastDayOfMonth = this.storeLastDate();

this.setState({
lastDayOfMonth: lastDayOfMonth
}, () => {
this.setState({ currentLastDate: this.curLastDate() });
}) // curLastDate as callback, which will be executed after setting state
}

关于javascript - 如何在构造函数中初始化依赖于另一个方法值的状态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56367828/

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