根据从下拉菜单中选择的对象来更新状态

时间:2019-03-28 01:43:29

标签: reactjs typescript state jsx

我有一个名为TaskTypes的对象,在对象内部看起来像这样

-LJLQR7lVkbzsxAZC3JI: {code: "Pest & Disease", colour: "0xf2473f", deleted: null, subTypes: {…}} -LJLQR7mZaeBNnEhdHtU: {code: "Health & Safety", colour: "0x8c5de4", deleted: null, subTypes: {…}} -LJLQR7mZaeBNnEhdHtZ: {code: "Structure", colour: "0x6b8e23", deleted: null, subTypes: {…}} -LJLQR7mZaeBNnEhdHtl: {code: "Repairs & Maintenance", colour: "0x66a9fb", deleted: null, subTypes: {…}} -LJLQR7nJdpun5Tugh39: {code: "Reminders", colour: "0xf2bb61", deleted: null, subTypes: null} -LUDgbjHzQpktk34u8-4: {code: "Sample", colour: "0x2196f3", deleted: null, subTypes: {…}} -L_dAY_Aju0IBGwY9VVA: {code: "test", colour: "0x03a9f4", deleted: null, subTypes: null}

第一个随机字符串是对象ID。

我希望每次选择这些对象之一时都更新taskId的状态,例如,如果我从下拉列表中选择“病虫害”,则taskId将为“ -LJLQR7lVkbzsxAZC3JI”

我创建了一个函数来实现此目的,但是状态并未更新。

this.state = { id: "", taskId: null,
               taskSubId: null,
               taskSubSubId: null }

setTaskType = (id: string) => {
        console.log("ID:", id)
        console.log("id.length:", id.length)
        console.log("stateTaskId", (this.state as any).taskId)
        if (id.length > 0) {
            console.log("setTaskTypeFunction", this.props.metadata.TaskTypes)
            this.setState({ id: id, taskId: id, taskSubId: null, taskSubSubId: null, taskType: Object.assign({}, this.props.metadata.TaskTypes[id]) })
        } 
    }

这里有我的JSX

<select className="input-field-slider dropdown w-select" onClick={() => this.setTaskType("")}>
   <option key={taskId} value={taskId}>Select A Category</option>
     {
        Object.keys(taskTypes)
         .sort((a, b) => taskTypes[a].code.toLowerCase() > 
                     taskTypes[b].code.toLowerCase() ? 1 : -1)                                                      
          .map(taskId =>
<option onClick={() => this.setTaskType(taskId)} value={taskId} key={taskId}>{taskTypes[taskId].code}</option>)}
</select>

到目前为止,我正在下拉列表中显示整个对象(病虫害等),但是状态尚未更新

1 个答案:

答案 0 :(得分:1)

进行一些修改可能会有所帮助。

选择更改处理程序

setTaskType = (event) => {
  const id = event.target.value;
  // continue with the rest of code
}

JSX选择元素

<select className="input-field-slider dropdown w-select" value={this.state.taskId} onChange={this.setTaskType}>
  <option value=''>Select A Category</option>
    {Object.keys(taskTypes)
      .sort((a, b) => taskTypes[a].code.toLowerCase() > 
                     taskTypes[b].code.toLowerCase() ? 1 : -1)                                                      
      .map(taskId => 
        <option value={taskId} key={taskId}>{taskTypes[taskId].code}</option>
    )}
</select>

访问mongo docs

了解更多详细信息