【发布时间】:2022-01-22 22:09:14
【问题描述】:
我使用 React 快 2 个月了,但遇到了一个问题。我项目的目标是使用 react-trello 构建一个任务监控工具。
我有我的 App 组件(我提供的所有代码都是这个组件/类的一部分):
class App extends Component {
constructor(props) {
super(props);
this.showTag = this.showTag.bind(this);
this.state = {
isLoaded: false,
tags: [],
currentInfo: "announcement",
info: [],
numOfTasks: 0,
openTasks: [],
criticalTasks: [],
manilaTasks: [],
darmstadtTasks: [],
montevideoTasks: [],
completedTasks: [],
isOpen: false // for task edit
}
}
我想每分钟检查我页面上的任务数是否与我的数据库中的任务数相匹配。这就是为什么我将 numOfTasks 添加到状态中,该状态设置为显示任务的值:
componentDidMount() {
// get all active Task an asign them to their column
fetch("/getTasks")
.then(res => res.json())
.then(
(result) => {
this.setState({numOfTasks: result.length})
//for mismatch-check
//console.log(this.state.numOfTasks) logs correct value
result.map(task => {
if (task.status === 'Open') {
this.setState({
openTasks: this.state.openTasks.concat(task)
});
}
if (task.status === 'Critical') {
this.setState({
criticalTasks: this.state.criticalTasks.concat(task)
});
}
if (task.status === 'RTC Manila') {
this.setState({
manilaTasks: this.state.manilaTasks.concat(task)
});
}
if (task.status === 'TO Darmstadt') {
this.setState({
darmstadtTasks: this.state.darmstadtTasks.concat(task)
});
}
if (task.status === 'RTC Montevideo') {
this.setState({
montevideoTasks: this.state.montevideoTasks.concat(task)
});
}
if (task.status === 'Completed') {
this.setState({
completedTasks: this.state.completedTasks.concat(task)
});
}
})
},
(error) => {
this.setState({
error
});
}
)
}
正如你所见,我已经评论过它将正确的值记录到控制台,例如最初它是零,但如果数据库中有两个任务,它会更改为两个。现在到主要问题,我天真地做了以下事情:
//scheduled function that checks if there is a mismatch between the
// number of task previously loaded (displayed on the board)
// true reload to display all active tasks
// false do nothing
reloader = setInterval(() => {
const {numOfTasks} = this.state
console.log(this.state)
fetch("/getTasks")
.then(res => res.json())
.then(
(result) => {
if (result.length !== numOfTasks) {
//console.log(result.length )
//console.log(numOfTasks)
//window.location.reload();
}
else {
// do nothing
}
},
(error) => {
this.setState({
error
});
}
)
}, 60000);
console.log 在这里记录第一个零(初始值)和第二个(只是一个示例),但 if 语句始终采用零值,因此每 60000 毫秒刷新一次页面。
有没有人可以解决这个问题? 谢谢你:)
【问题讨论】:
标签: javascript reactjs trello