【问题标题】:Matching url params in Ionic with React将 Ionic 中的 url 参数与 React 匹配
【发布时间】:2020-04-16 16:18:57
【问题描述】:

我正在开发一个FunctionalComponent,它将在Ionic 和React 中呈现项目列表。该组件将被重复用于每种类型的项目状态。我将项目的状态作为url-param 传递。

我想获取url-param并将其显示为列表标题并使用它来调用匹配项的API。将List-Componenturl 参数的matchrenders 渲染为未定义。

如何获取组件中的url参数?

在 Dashboard.tsx:

上链接到 List-Page
<IonCard className="card-body" href="/list/onschedule">

App.tsx:

<IonRouterOutlet>
    <Route exact path="/login" component={Login} />
    <Route exact path="/" render={() => <Redirect to="/dashboard" />} />
    <PrivateRoute path="/dashboard" component={Dashboard} exact={true} />
    <PrivateRoute path="/list/:status" component={List} />
</IonRouterOutlet>

在PrivateRoute组件中,我为道具放置了console.log,它得到了参数:

List.tsx:

interface StatusMatchProps extends RouteComponentProps<{
  status: string;
}> {}

const List: React.FunctionComponent<StatusMatchProps> = ({match}) => {
  console.log("match: " + match)

  return (
    <>
      <IonTitle>{match.params.status}</IonTitle>
  );
};

Chrome 的控制台输出:

【问题讨论】:

  • 渲染列表组件 url 参数的匹配渲染为未定义。 列表组件是如何渲染的?是作为独立组件渲染还是在路径与声明的 PrivateRoute 的路径匹配时渲染?

标签: reactjs typescript ionic-framework react-router url-parameters


【解决方案1】:

问题在于PrivateRouteComponent 没有传递道具。这是组件的工作版本:

interface PrivateRouteProps extends RouteProps {
  component: any
}

export const PrivateRoute: FunctionComponent<PrivateRouteProps> = ({ component: Component, ...rest }) => (

<Route {...rest} render={props => {
    const currentUser: string | null  =  localStorage.getItem("userID");

    if (!userID) {
        // not logged in so redirect to login page with the return url
        return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
    }

    // authorised so return component
    return <Component {...props} />
  }} />
); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2016-08-26
    • 1970-01-01
    相关资源
    最近更新 更多