React Link更新网址,但不更新视图

时间:2018-05-17 09:47:02

标签: javascript reactjs

我遇到的问题是,当我使用链接从同一组件导航到相同的组件(具有另一个id)时,url会更新,但组件本身不会更新。从其他地方导航到组件时,一切都很顺利。刷新它也有效。

我指的是 EditResultForm 组件。

我从index.js渲染所有内容:

// React router import
import {BrowserRouter as Router} from 'react-router-dom'

ReactDOM.render((
        <Router>
        <App />
        </Router>
), document.getElementById('root'));

registerServiceWorker(); 

App.jsx根据特定条件呈现不同的组件:

  render() {
    if (this.state.authorized) {
      return (
        <div className="App">
        {this.state.hide ? null : 
          <Header username={this.state.username} changeUsername={this.usernameChangedHandler} authorize={this.authorizeHandler} /> }
          <Main changeUsername={this.usernameChangedHandler} authorize={this.authorizeHandler} authorized={this.state.authorized} hideHandler={this.hideHandler}/>
        </div>
      );
    } else {
      return (<div><LoginForm changeUsername={this.usernameChangedHandler} authorize={this.authorizeHandler} authError={this.state.authError} />
        <Route exact path="/register" component={RegisterForm} /></div>);
    }
  }
}

然后main渲染所有路线:

  render() {
    return (
      <div>
      <main className="container-fluid fill">

        <Switch>
          <Route path="/login" render={() => <LoginForm changeUsername={this.state.changeUsername} authorize={this.state.authorize} />} />
          <PrivateRoute exact path="/" component={Home} />

          <PrivateRoute exact path="/result" component={Result} />
          <PrivateRoute path="/result/update/:id" component={EditResultForm} />

          <Route exact path="/register" component={RegisterForm} />

        </Switch>
      </main>
      </div>
    );
  }

我已经阅读了有关阻止更新的文章,但我的组件确实收到了位置对象,因此我认为问题出在其他地方。

我在我的组件中尝试过类似的东西:

  componentDidMount() {
    this.props.history.listen((location, action) => {
      if (location.pathname !== this.props.location.pathname) {
        console.log(location, action);

        this.props.location.pathname = location.pathname;

        this.forceUpdate();
      }

    });
}

但那也没有用。有人知道这里的问题是什么吗?

提前致谢, 麦克

1 个答案:

答案 0 :(得分:0)

使用此作为参考,组件WillReceiveProps将解决此问题

React doesn't reload component data on route param change