ReactJS - 动态更新jsonschema下拉列表

时间:2017-05-12 18:41:04

标签: reactjs drop-down-menu jsonschema fetch-api

我浏览了很多帖子,觉得我可能会遗漏一些小事。我有一个jsonschema表单,在组件类之前定义了几个下拉列表。要填充它们,我使用componentDidMount中的提取并将返回的值推送到下拉列表中的枚举。在渲染时,下拉列表为空白,但如果我单击另一个选项卡并返回,则下拉列表将填充该值。如何在初始渲染时填充它?代码如下。

jsonschema:

const schema = {
  type: 'object',
  required: ['contextID'],
  properties: {
    contextID: { type: 'string', title: 'Context ID, enum: [], enumNames: [] }    
  }
}

componentDidMount fetch:

}).then(function(json) {
  this.setState({contextIDArray: json.List}, () => {
    schema.properties.contextID.enumNames.push(this.state.contextIDArray);
    schema.properties.contextID.enum.push(this.state.contextIDArray);
    console.log("SCHEMA:: ", schema.properties.contextID.enumNames);
  });
}.bind(this)).catch(() => {
  this.setState({
    value: 'no response - cb catch'
  })
})

1 个答案:

答案 0 :(得分:1)

如果您想要更改组件中的对象,则需要将DOM作为状态对象呈现该组件中的更改。创建一个状态对象,在构造函数中设置状态,然后在更新后将其作为支柱传递给表单。

你的功能中有这样的东西:

}).then(function(json) {
 this.setState({contextIDArray: json.List}, () => {
 schema.properties.contextID.enumNames.push(this.state.contextIDArray);
schema.properties.contextID.enum.push(this.state.contextIDArray);
this.setState({schemaState: schema});
 });
}.bind(this)).catch(() => {
 this.setState({
   value: 'no response - cb catch'
 })
})

然后在你的渲染中像:

render() {

    return (
        <div className="container">
            <Form
                schema={this.state.schemaState}
            />
        </div>
        )
      }

这将重绘DOM。您的下拉列表应该更新。