使用打字稿时,如何在位置更改上强制重新渲染?

时间:2018-06-22 12:15:49

标签: typescript react-router react-router-v4

我有两条基本路线,每条路线都使用参数“ / categories /:category”和“ / types /:type”。我还具有一个导航栏,该导航栏为每个路线及其子参数提供一个下拉菜单。如果我使用导航栏链接在应用程序按预期方式渲染的路线之间导航,但是如果我在任一路线中导航,则不会重新渲染。这是有问题的,因为在每种情况下该参数都用于显示不同的内容。刷新页面将呈现正确的内容。

官方建议(https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md)是使用高阶组件或向下传递位置道具。这是我想做的,应该很简单,但是遇到了困难。当我尝试将位置属性传递下来时,打字稿编译器抱怨:     (41,36):属性'location'在类型'IntrinsicAttributes&PageListProps&{children ?: ReactNode; }'。

// App.tsx
class App extends React.Component<any> {
  public render() {
    return (
      <Router>
        <div className="App">
          <header className="App-header">
            <Logo />
            <h1 className="App-title">Directory</h1>
          </header>
          <NavBar />
          <Switch>
            <Route exact={true} path="/" component={ABWs} />

            <Route path="/categories/:category" component={PagesByCategory} />
            <Route path="/types/:type" component={PagesByType} />
          </Switch>
        </div>
      </Router>
    );
  }
}

// PagesByCategory.tsx
import axios from "axios";
import * as React from "react";
import { RouteComponentProps } from "react-router-dom";
import { PageProps } from "../components/Page";
import PageList from "../components/PageList";

interface MatchParams {
  category: string;
}

export interface PagesByCategoryProps
  extends RouteComponentProps<MatchParams> {}

export interface PagesByCategoryState {
  pages: PageProps[];
}

export default class PagesByCategory extends React.Component<
  PagesByCategoryProps,
  PagesByCategoryState
> {
  public state = {
    pages: []
  };

  public componentDidMount() {
    const { category } = this.props.match.params;
    axios
      .get(`http://localhost:9000?categories=${category}`)
      .then(res => {
        //tslint:disable
        console.log(res.data);
        return res;
      })
      .then(res => this.setState({ pages: res.data }));
  }

  public render() {
    const { pages } = this.state;
    const { location } = this.props;
    return <PageList pages={pages} location={location} />;
  }
}

0 个答案:

没有答案