似乎React Router无法与Redux一起使用,单击App组件中的链接成功将'/ search'添加到URL,但它不会导航到搜索页面,导航仅在刷新页面后才发生点击链接,那么这里出了什么问题?
这是我的两个组成部分
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './index.css';
import App from './App';
import * as BooksAPI from './BooksAPI';
import registerServiceWorker from './registerServiceWorker';
import { createStore, applyMiddleware } from 'redux';
import { bookReducer } from './reducers/BookReducer';
import thunk from 'redux-thunk';
import {BrowserRouter as Router} from 'react-router-dom';
const middleware = [thunk];
const store = createStore(bookReducer, [], applyMiddleware(...middleware));
ReactDOM.render(
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>,
document.getElementById('root')
);
registerServiceWorker();
App.js
import React, { Component } from 'react';
import { connect} from 'react-redux'
import BookShelf from './components/BookShelf'
import AllShelves from './components/AllShelves'
import Header from './components/Header';
import SearchPage from './components/SearchPage';
import * as BooksAPI from './BooksAPI';
import { Route } from 'react-router-dom';
import { Link } from 'react-router-dom';
import './App.css';
class App extends Component {
componentWillMount() {
this.props.fetchBooks();
}
render() {
console.log(this.props.books)
return (
<div className="App">
<Header />
<Route exact path="/" render={(props) => <AllShelves />} />
<Route path="/search" render={(props) => <SearchPage />} />
<div className="open-search">
<Link to="/search" />
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
books: state
}
}
const mapDispatchToProps = (dispatch) => {
return {
fetchBooks: () => {
BooksAPI.getAll().then(books => dispatch({
type: 'FETCH_BOOKS',
books
}))
},
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
所以为什么单击链接不会导致导航到搜索页面,而仅将'/ search'添加到URL。
答案 0 :(得分:1)
您可能需要应用withRouter
才能使其正常工作。
import {withRouter , BrowserRouter as Router} from 'react-router-dom';
// your code here
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
我建议阅读有关如何将反应路由器与 Redux 集成的官方文档 https://reacttraining.com/react-router/web/guides/redux-integration