【问题标题】:URL changes, but component doesn't rendered with react - typescriptURL 更改,但组件未使用 react 渲染 - 打字稿
【发布时间】:2020-12-31 02:00:08
【问题描述】:

我正在尝试以编程方式更改 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-history react-tsx


    【解决方案1】:

    好的!

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

    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');
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-04
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 2021-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多