2016-01-07 37 views
3

我使用Redux和redux-simple-router。redux-simple-router - 根據URL執行操作

這是我正在嘗試做的。用戶點擊如下URL: http://localhost:3000/#/profile/kSzHKGX 其中kSzHKGX是配置文件的ID。這應該路由到配置文件容器,填寫配置文件的詳細信息,編號爲kSzHKGX

我的路線是這樣的:

export default (
    <Route path="/" component={App}> 
    ... 
    <Route path="profile" component={Profile} /> 
    ... 
    </Route> 
) 

所以打上面的鏈接會給我Warning: [react-router] Location "undefined" did not match any routes

我的容器是這樣的:

@connect(
    state => state.profile, 
    dispatch => bindActionCreators(actionCreators, dispatch) 
) 
export class Profile extends Component { 
    constructor(props) { 
    super(props) 
    } 
    componentDidMount() { 
    const { getProfileIfNeeded, dispatch } = this.props 
    getProfileIfNeeded() 
    } 
    render() { 
    return (
     <section> 
     ... 
     </section> 
    ) 
    } 
} 

所以通常我的容器也只是在Redux中像往常一樣從國家填充。

基本上我需要在路線中做一些通配符。比我需要將URL傳遞給將從API中提取正確配置文件的操作。問題是,是否可以使用react-simple-router?我可以用UPDATE_PATH以某種方式做到這一點嗎?它會是適當的Redux方式嗎?還是應該使用別的東西?

+3

我懷疑你的路由器配置有問題,因爲你不應該得到'未定義的 - 也許是錯誤的或缺少的歷史?你可能也想分享一下。但是對於你的URL,你需要定義一個類似'profile /:id'的路徑,然後你的組件會在它的道具中收到一個'params'對象,它具有你所需要的配置文件的id。 –

+0

你想從歷史角度看什麼?現在,當我將路由作爲profile /:id時,應用向API發出一個請求到「http:// localhost:5000/profiles/undefined」(???) –

+1

我的意思是,重新使用'歷史'庫。例如。 [基本演示](https://github.com/rackt/redux-simple-router/blob/master/examples/basic/app.js)可以直接使用,因此您的觀點有何不同?我們可以看到你的實施?如果在'Profile'組件上記錄'this.props',你看到了什麼? –

回答

2

繼喬希戴維·米勒的建議下,我做了我的路線看起來像這樣:

<Route path="admin/profile/:id" component={Profile} /> 

比我的容器得到這個方法從API配置文件:

componentWillMount() { 
    const { getProfile, dispatch } = this.props 
    getProfile(this.props.params.id) 
} 

而這種清理(沒有它我會有以前的配置文件顯示分裂負載的第二秒 - 我擊中API在componentWillMount之前)

componentWillUnmount() { 
    this.props.unmountProfile() 
} 

更新:

作爲替代清理,我使用的是Container Component Pattern考慮。基本上有外部組件做數據獲取並將數據傳遞給內部組件作爲道具。