2017-02-26 66 views
0

我正在學習React + ReactRouter以構建多步驟表單。我得到了在這裏工作的例子:https://www.viget.com/articles/building-a-multi-step-registration-form-with-react如何使用React路由器製作React多步驟表單

問題是這個例子沒有使用ReactRouter,所以URL在表單中永遠不會改變。作者提到「你可以設置每一步到一個自定義路線」,但是,我一直無法弄清楚如何讓這個工作。如何更新當前渲染過程以使用ReactRouter。任何指針讚賞。由於

render: function() { 
    switch (this.state.step) { 
     case 1: 
    return <AccountFields fieldValues={fieldValues} 
          nextStep={this.nextStep} 
          saveValues={this.saveValues} /> 
     case 2: 
    return <SurveyFields fieldValues={fieldValues} 
          nextStep={this.nextStep} 
          previousStep={this.previousStep} 
          saveValues={this.saveValues} /> 
     case 3: 
    return <Confirmation fieldValues={fieldValues} 
          previousStep={this.previousStep} 
          submitRegistration={this.submitRegistration} /> 
     case 4: 
    return <Success fieldValues={fieldValues} /> 
    } 
} 

我已經試過:

render: function() { 
     switch (this.state.step) { 
      case 1: 
     return <AccountFields fieldValues={fieldValues} 
           nextStep={this.nextStep} 
           saveValues={this.saveValues} /> 
      case 2: 
         browserHistory.push('/surveyfields') 
      case 3: 
         browserHistory.push('/confirmation') 
      case 4: 
         browserHistory.push('/success') 
     } 
    } 

修訂

.. 
     case 2: 
      <Route path="/surveyfields" component={SurveyFields}/> 
.. 

var Welcome = React.createClass({ 
    render() { 
    return (
     <Router history={browserHistory}> 
     <Route path='/welcome' component={App}> 
      <IndexRoute component={Home} /> 
      <Route path='/stuff' component={Stuff} /> 
      <Route path='/features' component={Features} /> 
      <Route path='/surveyfields' component={SurveyFields} /> 

     </Route> 
     </Router> 
    ); 
    } 
}); 

回答

1

如果您的路由他們這個樣子,從過渡比如說,/surveyfields/success不會影響影響的狀態全部是Survey組件。

<Route path="/surveyfields" component={Survey}/> 
<Route path="/confirmation" component={Survey}/> 
<Route path="/success" component={Survey}/> 

React Router會更新道具並觸發渲染。如果要根據URL呈現不同的內容,請在render方法中使用此方法。

if(this.props.location.pathname==="/surveyfields") 
    return (
    <span> 
     survey things 
     <Button onClick={() => this.props.history.push("/confirmation")}>next page</Button> 
    </span>) 
if(this.props.location.pathname==="/confirmation") 
    return <span>do you want to do this</span> 

單擊按鈕將導航到下一頁。道具組件的React路由器會插入locationhistory道具。

+0

謝謝。我將'browserHistory.push('/ surveyfields')'改爲'' - 雖然它加載了React組件SurveyFields,但它不會更改我的URL使用反應路由器的目標...爲什麼路由URL不更改?以上更新 – AnApprentice

+1

你不應該改變渲染方法中的狀態或URL,當你改變狀態時想象一個無限循環,你觸發一個渲染,反過來改變狀態......我會在'this.saveValues'方法中改變URL狀態 – aitchnyu

+1

並且只在路由器中使用路由,將其放在其他地方是未定義的行爲。所以'case 2:return ' – aitchnyu