this.props 使用 ApolloClient 时无法访问

this.props not accessible when using ApolloClient

我正在使用 apollo-boost,我已经创建了一个 ApolloClient,我想在突变 运行 之后做一些重定向,但我无法访问道具

index.js

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
import { ApolloProvider } from "react-apollo";
import ApolloClient from "apollo-boost";

import "./bootstrap";
import Routes from "./RoutesComponent";

const client = new ApolloClient({
  uri: "http://localhost:4000/graphql"
});

const Root = () => {
  return (
    <ApolloProvider client={client}>
      <BrowserRouter>
        <Routes />
      </BrowserRouter>
    </ApolloProvider>
  );
};

ReactDOM.render(<Root />, document.querySelector("#root"));

路由组件

import React, { Component } from "react";
import { Route, Switch } from "react-router-dom";

import Register from "./authenticate/register/RegisterComponent";
import Login from "./authenticate/login/LoginComponent";
import Product from "./customers/product/ProductComponent";
import AddProduct from "./customers/add-product/AddProductComponent";
import Products from "./customers/products/ProductsComponent";
import AdminProduct from "./admin/product/ProductComponent";
import AdminProducts from "./admin/products/ProductsComponent";

class RoutesComponent extends Component {
  render() {
    return (
      <Switch>
        <Route path="/products/new" render={() => <AddProduct />} />
      </Switch>
    );
  }
}
export default RoutesComponent;

添加产品组件

import React, { Component } from "react";

class AddProductComponent extends Component {
  render() {
    console.log(this.props);
    return (
      <div>
        <h1>AddProductComponent</h1>
      </div>
    );
  }
}
export default AddProductComponent;

this.props 在控制台中显示 {}

为了缓解这种情况,我还尝试使用 history 包,它更改了 url 但重定向不起作用

我可以使用 state 进行重定向,但我宁愿使用 history prop 而不是 state。

如有任何建议,我们将不胜感激。

Route 的渲染函数将 props 作为参数,由于您没有传递它,它在组件中将不可用

<Route path="/products/new" render={() => <AddProduct />} />

固定:

<Route path="/products/new" component={AddProduct} />