【问题标题】:React-select not clearing current selection and allowing null to be selectedReact-select 不清除当前选择并允许选择 null
【发布时间】:2017-11-10 23:13:31
【问题描述】:

我确信这很简单,但我已经做了好几个小时了...... 我有一个 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>)

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多