簡體   English   中英

使用react-router-redux訪問參數

[英]Accessing params with react-router-redux

我正在使用react-router-redux( https://github.com/ReactTraining/react-router/tree/master/packages/react-router-redux

安裝

npm install --save react-router-redux@next

像這樣實現:

<Route path='/resource/:id' component={Resource}/>

我正在嘗試訪問容器中id的參數,如下所示:

const mapStateToProps = (state, ownProps) => {
  console.log(ownProps)
  return {...state.resource, id: ownProps.params.id}
}

如react-router-redux文檔中所示。

我收到一個錯誤,說明ownProps.params是未定義的。 這樣可行:

const mapStateToProps = (state, ownProps) => {
  return {...state.resource, id: ownProps.match.params.id}
}

但是,當我記錄ownProps時,我發現ownProps.match.params.id包含我需要的id。

這是實施中的變化還是我實施了錯誤的路線? 謝謝

我知道它已經是封閉的問題,但我認為這對其他人來說是有用的信息

我正在使用相同的版本,這是我無法訪問match時獲取params的任務的解決方案:

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

const { params } = createMatchSelector({ path: '/resource/:id' })(state);

console.log(params.id); 

我在redux-saga使用它,而不是在組件中。 對於你的情況,最好使用react-router道具並從props.match.params.id獲取params

npm install --save react-router-redux@next

使用上面的命令,您可能已經安裝了react-router-redux 5的alpha版本,並且您正在使用react-router v4。

正如他們在https://github.com/reactjs/react-router-redux自述文件中提到的那樣, react-router-redux版本5目前正在其他地方積極開發。

這個repo用於react-router-redux 4.x,它只與react-2.x和3.x兼容

react-router-redux的下一個版本將是5.0.0,並將與react-router 4.x兼容。 它目前正在那里積極開發。

因此,您引用的文檔對您使用的版本無效。

您的實現沒有任何問題,您可以通過ownProps的match繼續訪問params

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM