我尝试使用处于状态的选项创建动态选择。
我尝试了两件事:
const renderFieldSelect = ({ name, label, templateList}) => {
if(templateList && templateList.entities) {
return (
<div>
<div className="col-md-4" >
<label>{label}</label>
</div>
<div className="col-md-4">
<Field
className="form-control"
name={name}
component="select"
>
{
templateList.result.map((type, index) =>
return <option value={templateList.entities.template[type].id}>{templateList.entities.template[type].name}</option>
)
}
</Field>
</div>
</div>
)
}else {
return <div></div>
}
//... more stuff
class Bla extends Component {
//... more stuff
render(){
return (
<div>
<Field
component={renderFieldSelect}
name='templateList'
label='label'
templateList={this.props.templateList}
/>
<Field
component="input"
name='addNewOption'
type='text'
/>
<button onClick={addOption}>Add new option</button>
</div>
)
}
}
&#13;
但是当我更新templateList(使用输入和按钮)时,对象不会重新渲染新的 选项(我觉得很奇怪)。我知道addOption函数正在工作,因为它通过它的reducer
答案 0 :(得分:4)
根据您提供的信息,很难确定您的问题。
例如,您没有提供reducer或addOption函数。
在任何情况下,我都会编写一个快速示例,演示代码的这部分应该工作。因为你没有提供,所以我不能代表还原件。我今天不会编码。
也许这至少会为您提供一些证据,证明问题出在代码的其他方面。
import React, {Component} from 'react'
import {Field, reduxForm, formValueSelector} from 'redux-form'
import {connect} from 'react-redux'
const renderFieldSelect = ({ name, label, templateList }) => {
if (templateList && templateList.entities) {
return (
<div>
<div className="col-md-4">
<label>{label}</label>
</div>
<div className="col-md-4">
<Field
className="form-control"
name={name}
component="select">
{
templateList.result.map((type, index) => {
return (<option value={templateList.entities.template[ type ].id}>{templateList.entities.template[ type ].name}</option>)
})
}
</Field>
</div>
</div>
)
} else {
return <div></div>
}
}
class Bla extends Component {
constructor(props) {
super(props)
this.state = {}
this.state.templateList = {}
this.state.templateList.result = ['type1', 'type2']
this.state.templateList.entities = {}
this.state.templateList.entities.template = {
type1: {id: 1, name: 'Type 1'},
type2: {id: 2, name: 'Type 2'}
}
}
render () {
return (
<div>
<Field
component={renderFieldSelect}
name='templateList'
label='label'
templateList={this.state.templateList}
/>
<Field
component="input"
name='addNewOption'
type='text'
/>
<button onClick={this.addOption.bind(this)}>Add new option</button>
</div>
)
}
addOption() {
let type = {id: this.props.addNewOption, name: this.props.addNewOption}
this.setState({
...this.state,
templateList: {
result: [...this.state.templateList.result, type.id],
entities: {...this.state.templateList.entities, template: {...this.state.templateList.entities.template, [type.id]: type}}
}
})
}
}
let bla = reduxForm({
form: Bla.name
})(Bla)
const selector = formValueSelector(Bla.name)
bla = connect(
state => ({
addNewOption: selector(state, 'addNewOption')
})
)(bla)
export default bla