【问题标题】:React Link updates url, but not the view [duplicate]React Link 更新 url,但不是视图 [重复]
【发布时间】:2018-10-27 12:55:32
【问题描述】:

我遇到的问题是,当我使用链接从同一个组件导航到同一个组件(具有另一个 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();
      }

    });
}

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

提前致谢, 迈克

【问题讨论】:

  • 你的状态更新正确吗?
  • 将您的更新逻辑放入您的componentWillReceiveProps 并在那里进行更新。
  • @konekoya 好的,非常感谢!这解决了我的问题。但这背后的原因是什么?为什么它适用于 componentWillReceiveProps 而不适用于 ComponentDidMount?那是因为当您从同一个组件导航到同一个组件时,它已经被渲染,因此 ComponentDidMount 永远不会再次被触发?
  • 对此无法 100% 确定。但我认为你是对的。 React 路由器不会重新安装组件,因此您必须使用componentWillReceiveProps。请注意,componentWillReceiveProps 将被弃用 >= React 17。

标签: javascript reactjs


【解决方案1】:

将此作为参考,WillReceiveProps 组件将修复此问题

React doesn't reload component data on route param change

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    相关资源
    最近更新 更多