React-select不清除当前选择并允许选择null

时间:2017-11-10 23:13:31

标签: ruby-on-rails reactjs api react-select

我确信这很简单,但我已经待了几个小时...... 我有一个react-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"
        />

在“React-Select元素”中单击“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 个答案:

答案 0 :(得分:1)

当您单击“x”时,您将向selectPriority()函数发送null,而不是对象。该错误告诉您null没有属性'value'(也没有标签)。

最简单的解决方案是在函数中测试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)
  }
}