gpt4 book ai didi

react-router-redux 不会在位置更改时更新页面

转载 作者:行者123 更新时间:2023-12-01 01:54:52 27 4
gpt4 key购买 nike

我在使用 react-router 的 redux 版本时运气不佳。当我将产品添加到购物车时,位置确实发生了变化,但页面没有更新。

到目前为止,这是我的设置。其他一切都与新路由器一起工作,将项目添加到购物车成功地从 REST 服务器返回。但是,在我的操作文件中使用 push 不会更新页面。

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import createHistory from 'history/createBrowserHistory';
import { ConnectedRouter, routerMiddleware } from 'react-router-redux';
import reducers from './reducers';
import App from './components/app';

const history = createHistory();
const store = createStore(
reducers,
applyMiddleware(routerMiddleware(history), thunk)
);

ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<App />
</ConnectedRouter>
</Provider>,
document.getElementById('app')
);

app.js

import React from 'react';
import { BrowserRouter as Router, Link, Route } from 'react-router-dom';

import Cart from '../containers/cart';
import Home from './home';
import Checkout from '../containers/checkout';
import Products from '../containers/products';


const App = () => (
<Router>
<div className="app">
<Route exact={true} path="/" component={Home} />
<Route path="/cart" component={Cart} />
<Route path="/checkout" component={Checkout} />
<Route path="/products/:id/:url_title" component={Products} />
</div>
</Router>
);

export default App;

./reducers

import { reducer as FormReducer } from 'redux-form';
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';

const rootReducer = combineReducers({
router: routerReducer,
other: otherReducers
});

export default rootReducer;

./actions

import { push } from 'react-router-redux';

export function addProduct(props) {
return dispatch =>
axios.post(`${ROOT_URL}/api`, props, config)
.then(response => {
dispatch(push('/cart'));
})
}

最佳答案

尝试 connecting app.js 到 redux store 并通过 mapStateToProps 注入(inject) router prop。即使您没有明确使用该 prop,您的组件现在也应该在该 prop 发生变化时重新渲染自身及其子项。

react-router 还提供了一个 withRouter高阶组件做类似的事情。但是,我在让它在组件树的多个级别使用 shouldComponentUpdate 的应用程序中工作时遇到了问题。

关于react-router-redux 不会在位置更改时更新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43442376/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com