【问题标题】:Can you call an async function in a DetailsList?您可以在 DetailsList 中调用异步函数吗?
【发布时间】:2021-12-08 07:16:49
【问题描述】:

我在 SPFx Web 部件中有一个异步函数,它从 SPO 列表中获取数据。

    public async getTabData(theList = "ListOfLinks") {

      console.log('getTabData');

      let web = Web(this.props.webURL);
web.lists.getByTitle("ListOfLinks").items.select(...colsToSelect).get();
      const items: any[] = await web.lists.getByTitle(theList).items.get();
      console.log('items:' + items);

是否可以从 DetailsList 中调用此函数?

我尝试这样做

<DetailsList          
                  items={this.getTabData(item.ListToShow)}

但它说...

Type 'Promise<any[]>' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more.ts(2740)
DetailsList.types.d.ts(60, 5): The expected type comes from property 'items' which is declared here on type 'IntrinsicAttributes & IDetailsListProps & { children?: ReactNode; }'
(JSX attribute) IDetailsListProps.items: any[]

谢谢 P

【问题讨论】:

    标签: reactjs sharepoint sharepoint-online spfx


    【解决方案1】:

    问题是&lt;DetailsList /&gt; 接受items prop 作为数组,而getTabData() 返回一个promise

    我要做的是为项目创建一个状态,在组件渲染到componentDidMount() 后调用getTabData() 函数,并在异步工作完成后更新getTabData() 内的items

    items 更新后,组件将使用新数据重新渲染。

    class YourComponent extends Component {
      constructor(props) {
        super(props);
        this.items = [];
      }
    
      componentDidMount() {
        this.getTabData(item.ListToShow);
      }
    
      public async getTabData(theList = "ListOfLinks") {
        let web = Web(this.props.webURL);
        web.lists
          .getByTitle("ListOfLinks")
          .items.select(...colsToSelect)
          .get();
        const items: any[] = await web.lists.getByTitle(theList).items.get();
        console.log("items:" + items);
    
        this.setState({ items });
      }
    
      render() {}
    }
    

    【讨论】:

    • 嗨 Moaaz 感谢您的帮助。 DEtailsList 来自 fluentui developer.microsoft.com/en-us/fluentui/#/controls/web/…
    • 如果我尝试将 useEffect 放入我的渲染方法中,我会收到此错误...找不到名称“useEffect”。
    • 哦,我应该知道你使用的是类组件,而不是函数。 useEffect 用于功能组件。在您的情况下,请使用componentDidMount()。将更新我的答案。
    • 更新了答案。
    • 感谢 ComponentDidMount 似乎只在第一次加载页面时加载。当我点击 PivotItems 时,它似乎没有被再次调用?
    猜你喜欢
    • 2014-06-14
    • 1970-01-01
    • 2019-08-18
    • 2018-06-26
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多