【问题标题】:How to pass data queried in one component to another component to use as a query variable?如何将一个组件中查询的数据传递给另一个组件以用作查询变量?
【发布时间】: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


    【解决方案1】:

    已修复? 我最终选择了只获取 URL,稍微清理一下,并将其用作查询的变量,并添加加载和错误状态:

    export const DataDetails: React.FunctionComponent = () => {
      const dirtyPath = location.pathname;
      const cleanPath = dirtyPath.replace(/%20/g, ' ').replace(/\//g, '');
    
      const { data, loading, error } = useQuery(GET_DATA, {
        variables: { name: cleanPath },
      });
    
      return (
        ...
      );
    };
    

    使用 React Router 时可用的另一种解决方案是:

    export const DataDetails: React.FunctionComponent = (props) => {
      const { data, loading, error } = useQuery(GET_DATA, {
        variables: { name: props.match.params.name },
      });
    
      return (
        ...
      );
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 2014-08-31
      • 2012-09-14
      • 2020-11-13
      • 2019-01-31
      相关资源
      最近更新 更多