【发布时间】:2019-05-14 20:11:39
【问题描述】:
在使用 withRouter 和 connect 方法后,我仍然无法弄清楚为什么我的视图没有随着 URL 的变化而更新。
当我从 "/" 导航到 "/about" 时,页面没有更新,但在重新加载时可以正常工作。
从 React DevTools,我可以看到我的 props.location 即使在重定向之后也没有改变。所以我的猜测是我在某个地方搞砸了 Redux 的实现。
App.js
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import Main from "./Main";
const actionCreators = {};
function mapStateToProps(state) {
return state;
}
function mapDispatchToProps(dispatch) {
const actions = bindActionCreators(actionCreators);
return { ...actions, dispatch };
}
const App = withRouter(connect(mapStateToProps, mapDispatchToProps)(Main));
export default App;
Main.js
import React from "react";
import Navbar from "./components/navbar/navbar.component";
import Footer from "./components/footer/footer.component";
const Main = props => (
<div>
<Navbar currentState="Home" />
{React.cloneElement(props.children, props)}
<Footer />
</div>
);
export default Main;
index.js
import React from "react";
import { Provider } from "react-redux";
import { render } from "react-dom";
import { Router, Route, Switch } from "react-router";
import { withRouter } from "react-router-dom";
import store, { history } from "./store";
import App from "./App";
import Home from "./containers/home/home.component";
import AboutPage from "./containers/aboutPage/aboutPage.component";
const MOUNT_POINT = document.getElementById("root");
const router = (
<Provider store={store}>
<Router history={history}>
<App>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={AboutPage} />
</Switch>
</App>
</Router>
</Provider>
);
render(
router,
MOUNT_POINT,
);
虽然我在 Redux 状态下得到了以下差异(如下所示),但在 React 状态中没有反映出来。
{
"type": "@@router/LOCATION_CHANGE",
"payload": {
"pathname": "/about",
"search": ","
hash ":",
"key": "wk0oya"
}
}
我相信我在链接redux 和react-router 时搞砸了。曾尝试过 withRouter 解决方案学分:https://stackoverflow.com/a/45036930/2302156。
我还尝试将选项从react-redux as per following API Guide 传递给connect 方法:
[pure] (Boolean): 如果为真,connect() 将避免重新渲染和调用 到 mapStateToProps、mapDispatchToProps 和 mergeProps(如果相关) state/props 对象根据它们各自的相等性保持相等 检查。假设被包装的组件是一个“纯”组件,并且 不依赖任何输入或状态,除了它的 props 和 选择 Redux 商店的状态。默认值:真
我的包依赖列表:
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-redux": "^5.0.7",
"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",
"react-router-redux": "^4.0.8",
"redux": "^4.0.0",
"redux-thunk": "^2.3.0"
谁能帮我解决这个问题?
【问题讨论】:
标签: reactjs redux react-redux react-router-v4 react-router-redux