【发布时间】:2020-01-09 14:52:17
【问题描述】:
我试图将一个路由组件中使用 Apollo Client 查询的值传递给另一个路由组件以用作查询中的变量。确切的错误是:“Uncaught TypeError: Cannot read property 'name' of undefined”。
共有三个组件:
App,路由器的根组件。
ComponentA,它通过 id 和 name 查询一组数据以显示每个项目的卡片列表。每个项目都有一个指向 ComponentB 的链接。
组件 B,它必须使用组件 A 引用的名称作为变量查询更多数据,以显示该项目的更多数据。
App.tsx
export const App: React.FunctionComponent = () => {
return (
<BrowserRouter>
<>
<Main>
<Switch>
<Route exact path="/" component={ComponentA} />
<Route path="/:name" component={ComponentB} />
</Switch>
</Main>
</>
</BrowserRouter>
);
};
组件A.tsx
const GET_DATAS = gql`
query GetDatas {
getDatas {
_id
name
}
}
`;
interface Data {
_id: string;
name: string;
}
export const Home: React.FunctionComponent = () => {
const { data } = useQuery(GET_DATAS);
return (
<>
<div>
{data.getDatas.map((data: Data) => (
<Link to={`/${data.name}`} key={data._id}>
<Card name={data.name} />
</Link>
))}
</div>
</>
);
};
ComponentB.tsx
const GET_DATA = gql`
query GetData($name: String!) {
getData(name: $name) {
_id
name
year
color
}
}
`;
interface Props {
name: string;
}
export const DataDetails: React.FunctionComponent<Props> = (props: Props) => {
const { data } = useQuery(GET_DATA, {
variables: { name },
});
return (
<>
<div>
<H1>{data.getData.name}</H1>
<p>{data.getData.year}</p>
<p>{data.getData.color}</p>
</div>
</>
);
};
查询运行良好,因为我在 Playground 中对其进行了测试,我尝试使用本地状态并使用 Link 传递道具但没有结果,但我仍然无法弄清楚如何传递要在 ComponentB 的查询中使用的值.
提前致谢!
【问题讨论】:
标签: reactjs react-router apollo react-apollo apollo-client