【问题标题】:Route path="/subject/:selectedSubject" does not change subject when navigated via < Link />通过 < Link /> 导航时,Route path="/subject/:selectedSubject" 不会更改主题
【发布时间】:2019-10-30 17:22:17
【问题描述】:

我正在尝试显示按主题过滤的文章。例如,当您直接访问path="/subject/:selectedSubject"(主题/技术)时,它可以完美运行。但是,如果您通过 &lt;Link to={"/subject/TECH"} /&gt; 导航,它将更改 URL,但不会加载新文章。

我试过:用"withRouter" 连接一切。 我知道&lt;Link/&gt; 正在改变redux 状态,但是那不是调用componentWillMount(),这是fetchArticles() 所在的位置。

所以,我的问题是,我应该将 fetchArticles 放在哪里,以便在触发时调用它。我试着把它放在render() 中,但它一直被不停地调用。或者,也许我是在用错误的方式处理这个问题。

PS:如果通过&lt;Link/&gt; 调用另一个路径,例如path="/",它会按预期工作(加载新文章)。

在应用程序/

<BrowserRouter>  
    <div>  
        <Route path="/" exact component={ArticlesList} />  
        <Route path="/subject/:selectedSubject" component={ArticlesList} />  
    </div>  
</BrowserRouter>

在文章列表/

componentDidMount() {
    if (this.props.match.params.selectedSubject) {
      const selectedSubject = this.props.match.params.selectedSubject.toUpperCase();
      this.props.fetchArticles(selectedSubject);
    } else {
      this.props.fetchArticles();
    }
  }

在链接/

    {this.props.subjects.map(subject => {  
        return (  
            <Link to={`/subject/${subject.name}`} key={subject.name}>  
                <li>  
                    <span>{subject.name}</span>  
                </li>  
             </Link>  
        );  
    })}

【问题讨论】:

    标签: reactjs routes react-redux react-router


    【解决方案1】:

    由于您对//subject/:selectedSubject 使用相同的组件,因此他没有调用mounting 生命周期方法,包括constructor()componentDidMount()

    您必须使用updating 生命周期方法,尤其是componentDidUpdate() 来处理组件的更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-01
      • 1970-01-01
      相关资源
      最近更新 更多