2016-07-29 241 views
2

我有一個todo應用程序,我試圖選擇一個項目,並將其發送到一個頁面進行編輯。我看了這篇文章Getting query parameters from react-router hash fragment,並注意到他們正在使用this.props.location.query反應路由器參數不工作

我想完成的是獲取查詢參數並將其顯示在輸入框中進行編輯。

import * as React from 'react' 
import { Router, Route, IndexRoute, hashHistory, browserHistory, Link }  from 'react-router' 
import {ITask, IStoreAction, ActionType} from '../model/TasksModel' 

import store from '../store/Store' 

interface TaskEditProp { 
task: ITask 

} 

class TaskEdit extends React.Component<TaskEditProp, {}>{ 
constructor() { 
    super(); 
    this.state = store.getState() 

    store.subscribe(() => { 
     this.setState(store.getState()) 
    }) 

    //todo: console.log(this.props.location); 

} 

onSave = (e) => { 
    e.preventDefault(); 
    var refs: any = this.refs; 
    var task: ITask = { 
     index: this.props.task ? this.props.task.index : 0, 
     text: refs.text.value, 
     done: false 
    } 

    var storeAction: IStoreAction = { 
     type: ActionType.EDIT_TASK, 
     task 
    } 

    store.dispatch(storeAction) 
    browserHistory.push('/') 
} 

onCancel = (e) => { 
    e.preventDefault(); 
    browserHistory.push('/') 
} 

render() { 

    const { props: { children } } = this; 
    return (
     <div className=""> 
      <h3>Edit Task</h3> 
      <form onSubmit={this.onSave}> 
       <fieldset className="form-group"> 
        <label for="task">Task</label> 
        <input type="text" ref="text" className="form-control" >{this.props.location}</input> 
       </fieldset> 
       <div className="btn-group"> 
        <button className="btn btn-primary" >Save</button> 
        <button className="btn btn-warning" onClick={this.onCancel} >Cancel</button> 
       </div> 
      </form> 

     </div> 
    ) 
} 
} 

export default TaskEdit; 

我假設我的界面不包含位置,所以道具不知道位置。

這裏是如何我的路線定義爲:

var Routes = (
    <Router history={browserHistory}> 
     <Route path="/" component={Tasks}> 
      <IndexRoute component={TaskList} /> 
      <Route path="/add" component={TaskAdd} /> 
      <Route path="/edit/:id" component={TaskEdit} /> 
     </Route> 
     <Route path="/about" component={About}/> 
    </Router> 
) 

AFER我的商店已經出動,我打電話browserHistory.push('/edit/'+task.index)它送我去正確的觀點,但我不能訪問查詢參數。我的代碼的其餘部分可以在https://github.com/crh225/HotReactAsp/tree/master/src/HotReactAsp/content找到謝謝!

回答

2

您可以打印this.props以查看道具是如何呈現的,並找到提取所需數據的正確方法。

我不知道你正在使用其中react-router版本,但我知道正確的方式來獲得查詢參數是:

let { id } = this.props.params; 

index: this.props.task ? this.props.task.index : 0, 

index: this.props.params.id ? this.props.params.id : 0,