如何使用react-router v4获取mapStateToProps中的params值?

时间:2017-06-13 13:16:12

标签: javascript reactjs redux react-router react-redux

我使用react-router v4,react-router-dom,redux和react-redux来使我的应用程序正常工作。但是当我想获得deckId时,我无法得到params,它在ownProps论证中只有子道具。

我的主要组件看起来像这样

import React from 'react';
import {render} from 'react-dom';
import {createStore, combineReducers} from 'redux';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import {syncHistoryWithStore, routerReducer} from 'react-router-redux';
import {Provider} from 'react-redux';

import * as reducers from './reducers';
reducers.routing = routerReducer;

import App from './components/App';
import VisibleCards from './components/VisibleCards';


const store = createStore(combineReducers(reducers));

const history = syncHistoryWithStore(createBrowserHistory(), store);

function run() {
let state = store.getState();
console.log(state);
render(
<Provider store={store}>
    <Router history={history}>
        <App>
            <Switch>
                <Route exact path='/'/>
                <Route path='/deck/:deckId' component={VisibleCards}/>
            </Switch>
        </App>
    </Router>
</Provider>,
document.getElementById('root'));
}

run();

store.subscribe(run);

这样的App组件

import React from 'react';
import Sidebar from './Sidebar';
import {connect} from 'react-redux';



const mapStateToProps = (props, { params: { deckId } }) => ({ deckId });

const App = ({ deckId, children }) => {
console.log(params);
return (
    <div className="app">
        <Sidebar/>
        <h1>Deck {deckId}</h1>
        {children}
    </div>
);
}

export default connect(mapStateToProps)(App);

我使用withRouter将redux连接到react-router,但它也没有任何帮助。我该怎么办 ? 有任何想法吗 ?

1 个答案:

答案 0 :(得分:0)

react-router params已从组件this.props.params移至this.props.match.params

您的mapStatesToProps似乎需要更新为ownProps.match.params.deckId