无法在 UI reactjs 中呈现 this.props.location.state 的对象

Cannot render objects of this.props.location.state in UI reactjs

我在 visual studio 2017 年使用 React 开发应用程序时还很陌生,用户在文本框中输入某个名称,然后在其下方出现一个列表,为他提供建议。当用户单击任何项​​目时,他将被重定向到另一个页面,其中显示了建议项目的更多属性。到目前为止,我已经使用 Link 将一个组件的状态传递给另一个组件,但无法在另一个组件中显示该状态的属性。下面是我的组件的打字稿代码。

Search.tsx:

class Users {
profileId: string;
firstName: string;
middleName: string;
lastName: string;
dateOfBirth: string;
}

class Data {
users: Users[];
}

class QueryDetails {
search: string;
returncount: number;
skip: number;
top: number;
}

class SearchResult {
queryDetails: QueryDetails;
data: Data;
}  

class SearhProps {
searchResult: SearchResult;
searchText: string;
}


export class Search extends React.Component<any, SearhProps> {
constructor() {
    super();
    this.state = { searchText: '', searchResult: new SearchResult };
    this.handleSearchTextChange = this.handleSearchTextChange.bind(this);
}

public render() {
    return <div>
        <div>
            <input value={this.state.searchText} onChange={this.handleSearchTextChange} type="text" />
        </div>
        <div>
            <ul>
                {this.state.searchResult.data ? this.state.searchResult.data.users.map((user, index) =>
                    <li key={index}>
                        <Link to={{ pathname: '/s', search: '?name=' + this.state.searchText, state: this.state.searchResult.data }} key={index}>
                            <span>{user.firstName + ' ' + user.lastName}</span>
                        </Link>
                    </li>
                ) : null}
            </ul>
        </div>
    </div>;
}

在 handleSearchTextChange 方法上,我点击了一个 api 端点并获取在文本框中输入的用户的所有信息,并仅显示必填字段,即建议列表中的名字和姓氏。

现在,由于所有信息都在 this.state.searchResult.data 中,我想将其传递给另一个具有路由“/s”的组件。该组件如下:-

SearchLanding.tsx:

class Users {
profileId: string;
firstName: string;
middleName: string;
lastName: string;
dateOfBirth: string;
}

class UsersList {
users: Users[]
}

export class SearchLanding extends React.Component<RouteComponentProps<{}>, {}>  {
constructor() {
    super();
}

public render() {
return <div>
const userList = this.props.location.state as UsersList; //<= Logging userList or this.props.location.state gives me {users: Array(3)} and i get all the info if i expand this array
//This div will contain blocks of div which will show all the information of the user. But for now i am trying to display only the first name of the user
{userList ? userList.users.map(e => {
                <h2>{e.firstName}</h2>
            }) : null} //<= This is where it is not working
<div>

有人能告诉我哪里错了吗?我在 this.props.location.state 中获得了必要的对象,但似乎无法显示它。任何帮助将不胜感激

这很可能是由 map 回调中 <h2>{e.firstName}</h2> 周围的大括号引起的。要么删除它们,要么使用 {return <h2>{e.firstName}</h2>},否则 map 的结果是 undefined 的数组。 render 中还有一些语法问题,但我认为这些问题部分来自 copy/pasting 代码。