2016-08-16 69 views
1

我有動態的JSON數據並且有一個自定義方法來通過JSON動態地在頁面上呈現表單。 JSON模式的原因是構建不預定義的各種表單。整個表單正在React與Redux狀態中重新排列

我已經連接Redux,以便下面的模式和formValues被指定爲這個類的道具。因此,表單正確地使用正確的標籤,正確的輸入字段類型等來呈現。當字段上發生onChange事件時,應用程序狀態(在formData下)正在被正確更新。但我注意到,當formData在應用狀態中發生變化時,整個表單會被重新渲染,而不僅僅是「特定的字段」。這是因爲我將表單值存儲爲FormData這樣的對象?我如何避免這個問題?

formData = { 
    userName: 'username', 
    firstName: 'firstName 
} 

實施例模式

const form = { 
    "fields":[ 
      { 
       "label":"Username", 
       "field_type":"text", 
       "name":"username" 
      }, 
      { 
       "label":"First Name", 
       "field_type":"text", 
       "name":"firstName" 
      } 
    ] 
    } 

Redux的狀態

const reducer = combineReducers({ 
    formSchema: FormSchema, 
    formData: Form 
}); 

// render方法

render() { 
     const { fields } = this.props.form, 
     forms = fields.map(({label, name, field_type, required }) => { 
     const value = value; //assume this finds the correct value from the "formData" state. 
     return (
     <div key={name}> 
      <label>{label}</label> 
      <input type={field_type} 
      onChange={this.onChange} 
      value={value} 
      name={name} /> 
     </div> 
    ); 
    }) 
} 

//平變化的方法(用於受控形式的輸入,更新字段中formData應用程序狀態)

onChange(event) { 
    this.props.dispatch(updateFormData({ 
     field: event.target.name, 
     value: event.target.value 
    })); 
} 

回答

0

從你的例子我不確定,但如果你在一個渲染()方法渲染整個事情,是的,組件將被再次呈現。這就是問題所在,組件。如果您嘗試擁有多個組件,則應儘可能將它們分開。否則,如果狀態改變,它會觸發重新渲染唯一的組件。 嘗試儘可能多地破壞它。

提示:(不知道他們是否申請,但也許)

  • 使用ref={}小號
  • 實施shouldComponentUpdate()

編輯:只是想過這個,但你存儲的字段的值在你的狀態?這不正確。請務必仔細閱讀有關受控組件的React指南。 (例如,嘗試使用普通的<span> s來代替輸入,並且聽onKeyPress,它會繼續工作嗎?如果不是,你可能會濫用值屬性)

+0

@ rom-grk-是的,值屬性正在更新國家。由於冗長,我沒有把所有的代碼放在這裏。我通過使用shouldComponentUpdate()做了上面的建議,它只更新了道具更改的組件。 – Dhana

相關問題