簡體   English   中英

使用 React & PnPJS 更新 SharePoint spfx 中的數組

[英]Updating an array in SharePoint spfx using React & PnPJS

我正在創建一個網絡應用程序,允許用戶更新他們的狀態和位置。

我在 SharePoint 上有一個數據列表,其中包含用戶的姓名、電子郵件地址、狀態(例如:在線、離線或忙碌)、位置(這是一個選擇字段)以及其他字段。

Web 應用程序只是 2 個不同的選擇字段。 這允許用戶更新他的狀態和位置。

當用戶訪問componentDidMount()上的頁面時,我將獲取用戶的電子郵件地址(因為他已登錄 SharePoint),然后過濾數據列表數組以查看其信息的元素(因此在MyList查找他的電子郵件地址。我現在MyList的部分是使用用戶選擇的選定響應更新MyList列表。

使用 PnP-JS 我發現這應該是可能的,這里有兩個顯示update()函數的鏈接。 https://github.com/SharePoint/PnP-JS-Core/wiki/Basic--Operations

https://github.com/SharePoint/PnP-JS-Core/wiki/Working-With:-Items

我的代碼在這里找到:

export default class SigninLocationWebpart extends React.Component<ISigninLocationWebpartProps, {Status: string, Location: string, userName: string, getEmail: string, selectedUser: any}> {

    constructor(props) {
        super(props);
        this.state = {
            Status: 'Online',
            Location: 'New York',
            userName: '',
            getEmail: '',
            selectedUser: {},

        };

        this.handleChangeStatus = this.handleChangeStatus.bind(this); 
        this.handleChangeLocation = this.handleChangeLocation.bind(this);   

    }

    handleChangeStatus(event) {
        const { value } = event.target;
        this.setState({ Status: value });
    }

    handleChangeLocation(event) {
        const { value } = event.target;
        this.setState({ Location: value });
    }


    private _onUpdate(event) { 
        event.preventDefault();

        //This is where I need help on updating list
        let list = pnp.sp.web.lists.getByTitle("MyList")

        //Instead of getting by ID i need to get by that selectUser array I believe
        list.items.getById(1).update({
            Status: this.state.Status, //User changing from Online to Offline
            Location: this.state.Location //User changing from New York to Los Angeles
        }).then(i => {
            console.log(i);
        });

    }       

    public componentDidMount() { 
        if (Environment.type === EnvironmentType.Local) {
        }
        else if (Environment.type === EnvironmentType.SharePoint || Environment.type === EnvironmentType.ClassicSharePoint) {

            //This gets the current users info and sets it to username and email
            sp.web.currentUser.get().then((response : CurrentUser) => {
                //console.log(response);
                this.setState({
                    userName: response["Title"],
                    getEmail: response["Email"],
                })
            })          


            //This gets the list of all all items in the list
            pnp.sp.web.lists.getByTitle("MyList").items.get().then((items: any[]) => {
                console.log(items);

                //Comparing email from sign in user and filtering items array to get that element
                var compareEmail = this.state.getEmail;
                console.log(compareEmail);

                let selectedUser =  _.filter(items, function(item) {
                    return item.Email_x0020_Address.toLowerCase() === compareEmail.toLowerCase();
                });
                console.log(selectedUser);


            });


        }
    }



    public render(): React.ReactElement<ISigninLocationWebpartProps> {
        return (

            <div className={ styles.signinLocationWebpart }>
                <h3>Hello {this.state.userName}</h3>

                <form onSubmit={this._onUpdate}>

                    <label>
                        Check In our Out
                    </label>
                    <select name="Status" value={this.state.Status} onChange={this.handleChangeStatus}> 
                        <option value="Online">Online</option>
                        <option value="Offline">Offline</option>
                        <option value="Busy">Busy</option>
                    </select>

                    <label>
                        Location
                    </label>
                    <select name="Location" value={this.state.Location} onChange={this.handleChangeLocation}> 
                        <option value="New York">New York</option>
                        <option value="Michigan">Michigan</option>
                        <option value="Los Angeles">Los Angeles</option>
                    </select>

                    <input type="submit" value="Submit" />

                </form>

            </div>
        );
    }
}

首先,不是獲取列表中的所有項目,然后過濾當前用戶,您應該只獲取當前用戶的項目。 一旦列表變大,您將通過檢索所有項目來執行大量開銷。

其次,您在評論中提到的是您需要指定要更新的項目的 ID。 因此,在您的componentDidMount ,在您獲得當前用戶的 List Item 后,將該 Item 保存在您的狀態中。

public componentDidMount() { 
    if (Environment.type === EnvironmentType.Local) {
    }
    else if (Environment.type === EnvironmentType.SharePoint || Environment.type === EnvironmentType.ClassicSharePoint) {

        //This gets the current users info and sets it to username and email
        sp.web.currentUser.get().then((response : CurrentUser) => {
            //console.log(response);
            this.setState({
                userName: response["Title"],
                getEmail: response["Email"],
            });

            pnp.sp.web.lists.getByTitle("MyList").items.filter("Email_x0020_Address eq '" + this.state.getEmail + "'").top(1).get().then((items: any[]) => {
                if (items && items.length) {
                    this.setState( { selectedUser: items[0] } );
                }
            });
        })          

    }
}

然后在更新時,您可以使用該項目的 ID 來保存它。

private _onUpdate(event) { 
    event.preventDefault();

    //This is where I need help on updating list
    let list = pnp.sp.web.lists.getByTitle("MyList")

    //Instead of getting by ID i need to get by that selectUser array I believe
    list.items.getById(this.state.selectedUser.ID).update({
        Status: this.state.Status, //User changing from Online to Offline
        Location: this.state.Location //User changing from New York to Los Angeles
    }).then(i => {
        console.log(i);
    });

}       

此外,您需要確保綁定您的提交處理程序,就像您在構造函數中為您的 onchange 處理程序所做的那樣:

this._onUpdate = this._onUpdate.bind(this);   

我還要補充一點,除非您確保使用所有可能的用戶預先填充列表,並始終使用新用戶對其進行更新,否則最好檢查您的_onUpdate是否為this.state.selectedUser == null || this.state.selectedUser.ID == null this.state.selectedUser == null || this.state.selectedUser.ID == null那么你應該創建一個新項目(並將新項目添加到你的this.state.selectedUser ),而不是更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM