2017-11-10 183 views
0

我相信這很簡單,但我一直盯着它幾個小時...... 我有一個反應選元素,我可以添加或編輯和更新,但無法弄清楚如何清除select並將DB字段設置爲null。陣營,選擇不清除當前的選擇,並允許空值來選擇

組件

  selectPriority(priority) { 
     this.updateAttribute("priorityId", priority.value) 
     this.updateAttribute("priority", priority.label) 
     } 

選擇元素

 <Select 
     name="select_priority" 
     value={proposalService.priorityId ? proposalService.priorityId 
       : null} 
     options={priorities.map(p => ({ 
      value: p.id, 
      label: p.name, 
      })) 
      .sort((a, b) => a.label < b.label)} 
     onChange={p => this.selectPriority(p) || null} 
     placeholder="Select Priority" 
     /> 

在陣營選元素點擊 「X」 時,控制檯錯誤

ProposalServiceForm.js:86 Uncaught TypeError: Cannot read property 'value' of null 
at ProposalServiceForm.selectPriority (ProposalServiceForm.js:86) 
at Object.onChange (ProposalServiceForm.js:342) 
at Object.setValue (Select.js:683) 
at Object.clearValue (Select.js:748) 
at Object.ReactErrorUtils.invokeGuardedCallback (ReactErrorUtils.js:69) 
at executeDispatch (EventPluginUtils.js:85) 
at Object.executeDispatchesInOrder (EventPluginUtils.js:105) 
at executeDispatchesAndRelease (EventPluginHub.js:43) 
at executeDispatchesAndReleaseTopLevel (EventPluginHub.js:54) 
at Array.forEach (<anonymous>) 

回答

1

當你點擊'x'時,你發送null到selectPriority()函數,而不是一個對象。錯誤是告訴你null沒有屬性的'值'(也沒有標籤)。

最簡單的解決辦法是在功能測試空然後分配給它:

selectPriority(priority) { 
    this.updateAttribute("priorityId", priority ? priority.value : null) 
    this.updateAttribute("priority", priority ? priority.label : null) 
    } 

或者:

selectPriority(priority) { 
    if (priority == null) { 
    this.updateAttribute("priorityId", null) 
    this.updateAttribute("priority", null) 
    } else { 
    this.updateAttribute("priorityId", priority.value) 
    this.updateAttribute("priority", priority.label) 
    } 
}