typescript - SPFx 使用 @pnp/sp 创建列表
问题描述
我正在尝试使用@pnp/sp创建自定义列表,在我的例程中我需要检查列表是否存在,如果不存在,我将创建列表并添加其列。
下面的代码有时会起作用,猜想是因为sp.web.*方法是异步的,它会导致问题。
那么,1)检查特定列表,2)如果列表不存在则添加列表,3)将字段添加到列表中的正确方法是什么?
sp.web.lists.ensure("SliceBox").then( List => {
List.fields.getByTitle("Body").get().catch( f => {
f.fields.addMultilineText("Body", 4, true, false, false, true);
});
List.fields.getByTitle("Link").get().catch( f => {
f.fields.addUrl("Link", UrlFieldFormatType.Hyperlink);
});
List.fields.getByTitle("Visible").get().catch( f => {
f.fields.addBoolean("Visible");
});
})
.catch( err => {
console.log("> Failure: ", err);
});
如果我尝试非常明确的方式(见下文)也没关系,它也会失败:
sp.web.lists.ensure("SliceBox").then( List => {
sp.web.lists.getByTitle("SliceBox").fields.getByTitle("Body").get().catch( f => {
f.fields.addMultilineText("Body", 4, true, false, false, true);
});
// ... shortened for brevity ...
})
.catch( err => {
console.log("> Failure: ", err);
});
解决方案
我的示例测试代码运行良好。
sp.web.lists.ensure("SliceBox").then( sliceBox => {
sliceBox.list.fields.getByTitle("Visible").get().catch( f => {
sliceBox.list.fields.addBoolean("Visible");
alert('fieldAdded');
});
})
更新:
尝试这个:
sp.web.lists.ensure("SliceBox").then( sliceBox => {
sliceBox.list.fields.getByTitle("Visible").get().catch( f => {
sliceBox.list.fields.addBoolean("Visible").then(f =>{
sliceBox.list.fields.getByTitle("Link").get().catch( f => {
sliceBox.list.fields.addUrl("Link", UrlFieldFormatType.Hyperlink);
alert('done');
});
})
});
})
推荐阅读
- database - 更新字段和值 mongoDB
- docker - 无法在 Ubuntu 仿生上运行 docker 守护进程
- amazon-web-services - get row by partition key on aws dynamodb
- javascript - 如何在 css/html/js 中移动图像?
- javascript - Discord Bot ReferenceError:未定义客户端
- c++ - 通用链接列表错误:LinkedList 不是类模板
- shell - 让我知道 sed'2!n;d' 的逻辑
- reactjs - React Context - 如何构建用户帖子
- math - JOML:透视矩阵不保留形状
- html - 导航包裹在标题中而不是?