如何显示传递给组件的参数以及如何为 reactjs 中的组件提供可选参数?

How to display parameters passed to a component and how to give optional parameters to a component in reactjs?

我正在 visual studio 2017 年使用 react with typescript 开发一个网页,我对它还很陌生。我在访问传递给组件的参数并将参数设为可选时遇到了一些问题。下面是我的代码:-

routes.tsx:

export const routes = <Layout>
<Switch>
    <Route path='/home/:id' component={Home} /> //<= this works, but i want id parameter to be optional. I tried (/:id) but the component does not render if i do this.
</Switch>
</Layout>

Home.tsx:

export class Home extends React.Component<RouteComponentProps<{}>, {}> {
public render() {
    console.log(this.props.match.params); //<= I can see the id which i pass in the console
    return <div>
       <h1>{this.props.match.params}<h1> //<= this does not work and gives me a runtime error 'Unhandled rejection Invariant Violation: Objects are not valid as a React child (found: object with keys {id}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons'
   </div>

1)如何为组件提供可选参数?
2)如何在Home组件中显示传入的参数?

如有任何帮助,我们将不胜感激。提前致谢

像这样使用?来传递可选参数:

<Route path="/home/:id?" component={Home}/>

Start reading here 了解更多

要显示变量,请使用 {this.props.match.params.id}。如果你想处理 id 不存在的情况,可以使用这样的东西:

{this.props.match.params.id || 'sorry lol no id is specified'}

澄清为什么会出现错误:"params" 是一个包含所有参数的对象。 React 不知道如何显示对象。如果你想显示一个对象,你可以使用 JSON.stringify(params) 但我认为这不是你要找的。

问题是你想要呈现对象,因为 this.props.match.params 指向整个对象,所以你要么必须进行字符串化,要么要求某些 属性 像 Id。

{JSON.stringify(this.props.match.params)}

{this.props.match.params.id}
ofcourse that for this thing you have to accept id as parametr /home/:id

由于您使用的是打字稿,这取决于您是在编写 class(Component) 还是函数,无论哪种方式,您收到的错误都是因为您没有正确输入它,但是由于您正在引用 this.props,我假设它是 class.

class App extends React.Component<Props> {}

interface Props {
    match: any;
}

是的,它的类型很弱,但是除非你直接从库中导入类型,否则你需要花一些时间来输入所有内容,而且在每个文件中都这样做是愚蠢的。

如@pgsandstrom 所说,使用 ? 传递可选参数对我有用。

至于从参数中检索 ID 属性,我所做的是为 this.props.match.params 创建一个对象,然后使用该对象检索 ID。以下是我使用的代码:-

let data = Object.create(this.props.match.params);

然后

data.id

将检索我的 ID 而不会在打字稿中给出任何编译错误