Машинопись: Тип 'Promise <{}>' нельзя назначить типу - PullRequest
0 голосов
/ 18 марта 2020

Я строю стол, используя таблицу материалов. Вот пример того, как должна быть построена таблица: https://material-table.com/# / docs / features / filtering

Я пытаюсь передать массив в data для заполнения полей из моего Userlist массива.

У меня есть это в моей componentDidMount() функции

    pnp.sp.web.lists.getByTitle("Team").items.get().then((items: any[]) => {
        //console.log(items); 
        const UserList = items.map((item) => {

            return {
                UsersName: item.Title,
                UserEmail: item.Email_x0020_Address,
                UserStatus: item.Status,
                UserLocation: item.Location,
                UserAdditional: item.Additional,                        
            }
        });
        //console.log(UserList);

        this.setState({ UserList: [...UserList] });

    });

В моем рендере у меня есть это:

        <MaterialTable
            title=""
            columns={[
            { title: 'Name', field: 'UsersName' },
            { title: 'Email', field: 'UserEmail' },
            { title: 'Status', field: 'UserStatus' },
            { title: 'Location', field: 'UserLocation' },                   
            { title: 'Additional', field: 'UserAdditional' },
            ]}
            data={new Promise((resolve,reject) => {
                (this.state.UserList)
            })}       
            options={{
            filtering: true
            }}
        />

Первоначально я имел data={this.state.Userlist}, но получал ошибку _this.props.data is not a function at MaterialTable.

Итак, я изменился и передал данные в обещании обойти ошибку, но теперь получаю эту ошибку:

 error TS2322: Type 'Promise<{}>' is not assignable to type '({ UsersName: any; } & { UserEmail: any; } & { UserStatus: any; } & { UserLocation: any; } & { UserAdditional: any; })[] | ((query: Query<{ UsersName: any; } & { UserEmail: any; } & { UserStatus: any; } & { UserLocation: any; } & { ...; }>) => Promise<...>)'.

1 Ответ

1 голос
/ 19 марта 2020

Я не обладаю обширными знаниями о ReactJS, в основном, я Angular парень, но при поиске я нашел это.

Ход выполнения:

Order of execution in react

Метод 1:

Измените метод с componentWillMount на UNSAFE_componentWillMount, так как componentWillMount устарел в 2018. Больше здесь https://dev.to/torianne02/componentwillmount-vs-componentdidmount-5f0n

UNSAFE_componentWillMount()
{
 this.setState({ UserList: [] });
  pnp.sp.web.lists.getByTitle("Team").items.get().then((items: any[]) => {
    //console.log(items); 
    const UserList = items.map((item) => {

        return {
            UsersName: item.Title,
            UserEmail: item.Email_x0020_Address,
            UserStatus: item.Status,
            UserLocation: item.Location,
            UserAdditional: item.Additional,                        
        }
    });
    //console.log(UserList);

    this.setState({ UserList: [...UserList] });
});
}

Метод2: В конструкторе инициализировать состояние:

constructor() {
    // Required step: always call the parent class' constructor
    super(props);

    // Set the state directly. 
    this.state = {
        UserList: [],
        //if you have any other state variables add here
    }
  }

Выполнить вызов get в componentDidMount

componentDidMount(){
    pnp.sp.web.lists.getByTitle("Team").items.get().then((items: any[]) => {
        //console.log(items); 
        const UserList = items.map((item) => {

            return {
                UsersName: item.Title,
                UserEmail: item.Email_x0020_Address,
                UserStatus: item.Status,
                UserLocation: item.Location,
                UserAdditional: item.Additional,                        
            }
        });
        //console.log(UserList);

        this.setState({ UserList: [...UserList] });
    })
}

В обоих случаях отображать функцию

render(){
   return ( <MaterialTable
   title=""
   columns={[
   { title: 'Name', field: 'UsersName' },
   { title: 'Email', field: 'UserEmail' },
   { title: 'Status', field: 'UserStatus' },
   { title: 'Location', field: 'UserLocation' },                   
   { title: 'Additional', field: 'UserAdditional' },
   ]}
   data={this.state.Userlist}      
   options={{
   filtering: true
   }}
/>)
}
...