简体   繁体   English

使用 React & PnPJS 更新 SharePoint spfx 中的数组

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

I'm creating a web app that allows the user to update their status and location.我正在创建一个网络应用程序,允许用户更新他们的状态和位置。

I have a data list table on SharePoint with the user's name, email address, status (for example: online, offline, or busy), location (which is a select field), along with other fields.我在 SharePoint 上有一个数据列表,其中包含用户的姓名、电子邮件地址、状态(例如:在线、离线或忙碌)、位置(这是一个选择字段)以及其他字段。

The web app is just 2 different select fields. Web 应用程序只是 2 个不同的选择字段。 Which allows the user to update his status and location.这允许用户更新他的状态和位置。

When the user accesses the page on componentDidMount() I'm getting the user's email addresses (since he's logged into SharePoint) and then filtering the data list array to view the element for his information (so looking for his email address in the MyList . The part I'm stuck at now is updating the MyList list with the selected response that the user selected.当用户访问componentDidMount()上的页面时,我将获取用户的电子邮件地址(因为他已登录 SharePoint),然后过滤数据列表数组以查看其信息的元素(因此在MyList查找他的电子邮件地址。我现在MyList的部分是使用用户选择的选定响应更新MyList列表。

Using PnP-JS i found this should be possible here are two links showing the update() function.使用 PnP-JS 我发现这应该是可能的,这里有两个显示update()函数的链接。 https://github.com/SharePoint/PnP-JS-Core/wiki/Basic--Operations https://github.com/SharePoint/PnP-JS-Core/wiki/Basic--Operations

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

My code found here:我的代码在这里找到:

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>
        );
    }
}

First of all, instead of getting all items in the List, and then filtering for the current user, you should get only the item(s) for the current user to begin with.首先,不是获取列表中的所有项目,然后过滤当前用户,您应该只获取当前用户的项目。 Once you list gets large, you would be performing a lot of overhead by retrieving all items.一旦列表变大,您将通过检索所有项目来执行大量开销。

Secondly, and what you allude to in your comments, is that you need to specify the ID of the item to update.其次,您在评论中提到的是您需要指定要更新的项目的 ID。 So, in your componentDidMount , after you get the List Item for the current user, save that Item in your state.因此,在您的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] } );
                }
            });
        })          

    }
}

Then at update time, you can use the ID of that item to save it.然后在更新时,您可以使用该项目的 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);
    });

}       

Additionally, you'll want to make sure you are binding your submission handler just like you are doing for your onchange handlers in your constructor:此外,您需要确保绑定您的提交处理程序,就像您在构造函数中为您的 onchange 处理程序所做的那样:

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

I will also add, that unless you've make sure to pre-populate the List with all possible users, and will always keep it updated with new users, it would be best in to put a check in your _onUpdate that if this.state.selectedUser == null || this.state.selectedUser.ID == null我还要补充一点,除非您确保使用所有可能的用户预先填充列表,并始终使用新用户对其进行更新,否则最好检查您的_onUpdate是否为this.state.selectedUser == null || this.state.selectedUser.ID == null this.state.selectedUser == null || this.state.selectedUser.ID == null then you should create a new item (and add the new item to your this.state.selectedUser ), instead of updating. 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