首页 > 解决方案 > URL 更改,但组件未使用 react 渲染 - 打字稿

问题描述

我正在尝试以编程方式更改 URL。

URL 已更改,但页面未刷新/呈现。我试图找到正确的答案超过 2 小时,但没有成功。我看到 URL 确实发生了变化,但组件没有刷新。我的布局组件如下所示:

export default class Layout extends Component {

public render() {

return (
  <BrowserRouter>
    <section className="layout">

      <header>
        <Header />
      </header>

      <main>
        <Switch>
          <Route path="/login" component={Login} exact />
          <Route path="/register" component={Register} exact />
          <Route path="/home" component={Main} exact />
          <Redirect from="/" to="/home"></Redirect>
        </Switch>
      </main>

      <footer>
        <Footer />
      </footer>

    </section>
  </BrowserRouter>
  );

 }
}

我的主要组件如下所示:

import React, { Component } from "react";
import './main.css'
import history from 'history/browser';

interface MainProps {

registerButton: string,
loginButton: string;
 }

export default class Main extends Component<MainProps, any>{

public constructor(props: MainProps) {
    super(props);
    
}

public render() {
    return (
        <div className="main">This is the Main Section
            <div>
                <button onClick={this.onRegisterButtonClicked}>REGISTER</button>
                <button onClick={this.onLoginButtonClicked}>LOGIN</button>
            </div>
        </div>);
}

private onLoginButtonClicked = () => {
history.push('/login');
 
}

private onRegisterButtonClicked = () => {
   
    
}
}

标签: html5-historyreact-tsx

解决方案


好的!

我试图删除接口(只是为了扩展没有道具的组件)

export default class Main extends Component<any>

然后命令:“this.props.history ....”被识别。

太棒了,我明白如果我想实现自己的道具,我必须在界面中添加另一个字段:

interface MainProps {
    history: BrowserHistory // This is the most important think
    registerButton: string,
    loginButton: string;
}

然后一切正常:

export default class Main extends Component<MainProps>{

private onRegisterButtonClicked = () => {
       
        this.props.history.push('/register');
    }
}

推荐阅读