【问题标题】:React-router-dom and Redux not rerendered the componentReact-router-dom 和 Redux 没有重新渲染组件
【发布时间】:2018-10-28 21:17:01
【问题描述】:

编辑:我找到了解决方案,我忘记了 routes.js 中的 switch 组件

我已经创建了这样的路线:/post/:id

我的routes.js 看起来像:

import React, { Component } from "react";
import { BrowserRouter, Route } from "react-router-dom";
import Posts from "./components/Posts";
import Post from "./components/Post";
class Routes extends Component {
  render() {
    return (
      <div>
        <BrowserRouter>
          <div>
            <Route exact path="/" component={Posts} />
            <Route path="/post/:id" component={Post} />
          </div>
        </BrowserRouter>
      </div>
    );
  }
}

export default Routes;

在我的/route 我列出了我所有的posts,当我点击其中一个时,我会更新网址http://localhost:3000/post/1

PS:我尝试使用 react-router 官方文档中所说的 withRouter 函数,但这种情况不适用于我的情况。

有问题的文件是post.js 它看起来像:

import React, { Component } from "react";
import { active_post } from "../actions/index";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { Link } from "react-router-dom";

class Post extends Component {
  componentWillMount() {
    this.props.active_post(this.props.match.params.id);
  }
  render() {
    console.log(this.props.post);
    return (
      <div>
        <h1>Detail d'un post</h1>
        <p>{this.props.match.params.id}</p>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    post: state.activePost
  };
}
function mapDispatchToProps(dispatch) {
  return bindActionCreators({ active_post }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(Post);

因此,例如,如果我在 URL 栏中手动输入 http://localhost:3000/post/3,例如,我有组件和 console.log() 以及我需要的帖子。

因此,如果您对此案有解决方案,我会接受。 谢谢你:)

【问题讨论】:

    标签: javascript reactjs redux react-router-dom


    【解决方案1】:

    您应该尝试在路由周围添加来自 react-router-dom 的 Switch

    <BrowserRouter>
        <div>
            <Switch>
                <Route exact path="/" component={Posts} />
                <Route path="/post/:id" component={Post} />
            </Switch>
        </div>
    </BrowserRouter>
    

    不要忘记在你的组件中包含来自 react-router-dom 的 Switch 模块。

    import { Route, Switch } from 'react-router-dom';

    【讨论】:

    • 就在你回答之前,我编辑了我的帖子......但我不明白为什么我们需要使用开关组件,你能解释一下吗?
    • 我刚刚查看了我自己的项目,发现我正在使用&lt;Switch&gt; 元素;)。但根据 react-router-dom 文档,Switch 确保只呈现与您的 url 匹配的第一个 &lt;Route&gt;。要了解有关 react-router-dom Switch 的更多信息,请查看以下链接:reacttraining.com/react-router/core/api/Switch。只是为了确保您的代码在添加 &lt;Switch&gt;? 时有效
    猜你喜欢
    • 2019-07-14
    • 1970-01-01
    • 2019-01-13
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2021-05-14
    • 2018-01-26
    • 2019-01-15
    相关资源
    最近更新 更多