使用ApolloClient时无法访问this.props

时间:2019-02-04 13:45:39

标签: reactjs react-apollo apollo-client apollo-boost

我正在使用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"));

RoutesComponent

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;

AddProductComponent

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显示{}

为缓解这种情况,我也尝试使用历史记录包,它会更改url,但重定向不起作用

我可以使用state进行重定向,但是我宁愿使用历史道具而不是state进行重定向。

对此表示任何建议。

1 个答案:

答案 0 :(得分:2)

Route的render函数以props作为参数,由于您没有传递它,因此它在组件中不可用

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

已修复:

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