1

几天来我一直在努力使用我认为简单且可重复使用的设置:

我正在使用Ionic 5 + React构建一个应用程序,它有一种新闻提要,多种内容汇集在一起​​。但与 Facebook 不同,它对每种内容(如事件、新闻等)都有不同的部分。

它们的行为都相似:每个部分都有一个标题,显示前 n 个项目,然后是“显示更多”链接。当然,单击这些项目之一会立即将用户带到详细信息页面。但是单击“显示更多”应该将用户带到一个页面,该页面只有扩展形式的特定列表(而不是假设前 3 个项目应该有 50 个,当到达该列表的末尾时,它应该加载下一个 50等等)。

因为提供每种内容的 API 使用不同的结构,所以嵌入了“部分组件sourceFn”的页面将两个函数 ,和mapFn, 传递给该组件。sourceFn处理该 n 项的加载,同时mapFn获取一个项并将该 API 数据结构映射到重用部分组件呈现其列表项所需的字段。

到目前为止一切顺利,它有效。但我被困在“显示更多”链接上。因为这里嵌入部分重定向到另一个页面,动态显示展开列表,所以需要知道对应的两个函数sourceFnmapFn。我尝试了很多方法(如https://stackoverflow.com/a/52064362),但每一个都失败了。有时它说某个地方props是未知的,但主要是因为DataCloneError: The Object could not be cloned

我为每一个提示感到高兴,如何做到(或做得更好)


以下是我尝试过的一些方法:(请在评论中告诉我,是否发布更多代码。我不想发送垃圾邮件 0:))

<Link to={'/page/list'+ id} id={id} title={title} sourceFn={sourceFn} mapFn={mapFn}>
    <IonButton slot="end" size="small" fill="clear" routerDirection="forward">
        Show more
        <IonIcon icon={chevronForwardOutline} slot="end" />
    </IonButton>
</Link>
<Link to={{
    pathname: '/page/list'+ id,
    state: {id: id, title: title, sourceFn: sourceFn, mapFn: mapFn}
}}>
    <IonButton slot="end" size="small" fill="clear" routerDirection="forward">
        Show more
        <IonIcon icon={chevronForwardOutline} slot="end" />
    </IonButton>
</Link>

和路线App.tsx

<Route
    exact={true}
    path={"/page/list/:sectionid"}
    render={(props) =>
        <List
            id={props.location.state.id}
            title={props.location.state.title}
            sourceFn={props.location.state.sourceFn}
            mapFn={props.location.state.mapFn}
        />}
/>

也很简单

<Route exact={true} path={"/page/list/:sectionid"} component={List} />
4

2 回答 2

1

我认为这需要Context

父组件可以在sourceFnmapFn来自的级别具有上下文:

const SomeContext = React.createContext()

export const useContextName = React.useContext(SomeContext)

<SomeContext.Provider value={{ sourceFn, mapFn }}>
  ...your routes here...
</SomeContext.Provider>

然后在您的 List 组件中,您可以执行以下操作:

import { useContextName } from 'wherever/you/are/exporting/from'

const List = (...your props ...) => {
   const { sourceFn, mapFn } = useContextName()
   ... the rest of your component ...
}

正如你所说,你的路线只是:

<Route exact={true} path={"/page/list/:sectionid"} component={List} />
于 2020-05-04T22:29:33.667 回答
0

我会建议这种React.Context方法,但您也可以像这样将函数的名称作为参数名称传递

<Route exact={true} 
  path={"/page/list/:mapFuncName/:sourceFuncName/:sectionid"} 
  component={List} />

在您的函数助手库中映射所有函数,以便可以通过特定名称访问它们。

mapFuncMap : {
  func1 : ()=> {}
  func2 : ()=> {}
  func3 : ()=> {}
}

sourceFuncMap : {
  func1 : ()=> {}
  func2 : ()=> {}
  func3 : ()=> {}
}

那么当你需要一个函数的时候,你可以在函数映射中使用函数的名字来访问它

sourceFuncMap['func1']();
于 2020-05-05T15:17:31.933 回答