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

问题描述 投票:2回答:3

我正在开发一个网页,使用视觉工作室2017年的打字稿,我很新。我在访问传递给组件的参数并使参数可选时遇到一些问题。以下是我的代码: -

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组件中显示传递的参数?

任何帮助,将不胜感激。提前致谢

reactjs typescript asp.net-core react-router-v4
3个回答
2
投票

使用像这样的?传递一个可选参数:

<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),但我不认为这是你正在寻找的。


2
投票

使用@pgsandstrom所说的?传递一个可选的参数为我工作。

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

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

然后

data.id

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


0
投票

问题是你想渲染Object,因为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

因为你使用的是打字稿,所以它取决于你是在编写类(组件)还是函数,无论你输入的错误是因为你没有正确输入它,但是因为你正在考虑this.props,我将假设它的类。

class App extends React.Component<Props> {}

interface Props {
    match: any;
}

是的,它的弱输入,但除非你直接从库中导入输入,否则你需要一段时间才能输入整个内容,而且在每个文件中执行它都会很愚蠢。

© www.soinside.com 2019 - 2024. All rights reserved.