我已经制作了一个LitElement,它应该对数据库中的所有用户进行控制台日志记录。我用nodejs和mysql做到了这一点。我能够从数据库中获取用户并对他们执行console.log操作,但是获取数据的脚本会重复运行,这是它不应该做的。这是我的LitElement。
export class AllUsers extends LitElement{
static get properties(){
return {
users : {type : String},
numberOfUsers : {type : Number},
location : {type: Object} // Needed for vaadin-router with litElements
}
}
constructor(){
super();
this.location = router.location
}
static styles = css`
:host {
display: block;
}
`;
render(){
return html `
<h1>ALL USERS</h1>
${this.getUsers()}
`;
}
getUsers(){
fetch('http://localhost:8081/getUsers', {
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
}
}).then(res =>{ res.json().then(data =>{
this.users = data
console.log(this.users)
this.numberOfUsers = this.users.length
})
}).catch((e) =>{
throw Error(e)
})
}
}
customElements.define('all-users', AllUsers)nodejs应用
app.get('/getUsers', function (req, res) {
db.query('SELECT * FROM users', function (err, result) {
if (err) {
res.status(400).send('Error in database operation.');
} else {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(result));
}
});
});要解决这个问题,必须做出哪些改变?
发布于 2021-05-06 04:55:54
此模板:
return html `
<h1>ALL USERS</h1>
${this.getUsers()}`;将this.getUsers()的输出呈现到模板中,但这是一个void,所以它基本上只是在每次呈现函数时再次触发该函数。
这里有几种不同的方法-我建议使用guard和until,以便仅在某些属性发生变化时获取用户,或者添加一个获取和缓存用户的ReactiveController,但最简单的方法可能是呈现用户,然后启动脚本获取用户。
首先更改模板以呈现用户:
return html `
<h1>ALL USERS</h1>
${this.users?.map(u => html`<span>User: ${u.name}</span>`)}`;然后简化您的getUsers,只填充它(请注意,使用async/await也要简单得多):
async getUsers() {
if(this.users)
return; // We already have users, don't get again
const res = await fetch('http://localhost:8081/getUsers', {
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
}
};
this.users = await res.json();
console.log(this.users);
this.numberOfUsers = this.users?.length;
}然后在firstUpdated或connectedCallback中调用this.getUsers()。
https://stackoverflow.com/questions/65327071
复制相似问题