【问题标题】:How to get params values in mapStateToProps using react-router v4?如何使用 react-router v4 获取 mapStateToProps 中的参数值?
【发布时间】:2017-06-13 13:16:12
【问题描述】:

我使用 react-router v4、react-router-dom、redux 和 react-redux 来使我的应用程序正常工作。但是当我想获取deckId时,我无法获取参数,它在ownProps参数中只有children prop。

我的主要组件是这样的

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,但它也无济于事。我该怎么办 ? 有任何想法吗 ?

【问题讨论】:

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


    【解决方案1】:

    react-router params 已从组件的 this.props.params 移动到 this.props.match.params

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

    【讨论】:

      猜你喜欢
      • 2019-03-20
      • 2017-08-30
      • 2018-01-10
      • 2019-08-07
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 2018-12-13
      相关资源
      最近更新 更多