Мне нужно передать состояние в defaultValue реквизиты в форме выбора. Я использую Ant.design для создания элементов формы. Когда я передаю состояние напрямую реквизиту defaultValue, значение состояния возвращается неопределенным. Итак, я создаю getDefaultSOFValue()
, чтобы получить значение из запроса и передать его в состояние. Вот мои компоненты кода:
SelectInput. js
import React from 'react'
import { Select } from 'antd'
import './SelectInput.css'
function SelectInput(props) {
return(
<Select defaultValue={props.defaultValue} value={props.value} onChange={props.onChange} placeholder={props.placeholderSelect} style={props.styleSelect}>
{props.valueSelect}
</Select>
)
}
export default SelectInput
Форма. js
import SelectInput from '../../../components/Form/Select/OrdinarySelect/SelectInput'
import { Select } from 'antd'
import 'antd/dist/antd.css'
import axios from 'axios'
class Form extends Component {
constructor(props) {
super(props)
this.getAccountName = this.getAccountName.bind(this)
this.getDefaultSOFValue = this.getDefaultSOFValue.bind(this)
this.handleSOFChange = this.handleSOFChange.bind(this)
this.state = {
inputSOF: '',
inputSOFDefaultValue: [],
valueSOF: ''
}
}
componentDidMount(){
// Fetch formInputData API
let formInputDataUrl = 'https://localhost:8000/formInputData'
let data = {
'inputPage': 'testInput'
}
axios.post(formInputDataUrl, data)
.then(res => {
// Assign "sof account" object to new Array.
let copyOfSoffAll = {
0: res.data.sofManagamentServiceResponse.sofAll.ccaccountList[1],
1: res.data.sofManagamentServiceResponse.sofAll.caaccountList[0],
2: res.data.sofManagamentServiceResponse.sofAll.caaccountList[1],
3: res.data.sofManagamentServiceResponse.sofAll.saaccountList[3]
}
this.setState({
inputSOFDefaultValue: res.data.sofManagamentServiceResponse.sofAll.ccaccountList[1],
inputSOF: copyOfSoffAll,
})
})
.catch(err => console.log(err))
}
getDefaultSOFValue(){
// this function used for get defaultValue and pass it to defaultValue prop in Select
}
getAccountName(){
return Object.values(this.state.inputSOF).map((value, index) => {
return <Option key={index} value={ value.accountBalance } >{ value.accountName } <br /> { value.accountNumber }</Option>
})
}
handleSOFChange(value){
this.setState({
valueSOF: value
})
}
render(){
return(
<div style={{ width: '100%' }}>
<div className='container'>
<SelectInput
defaultValue={ this.getDefaultSOFValue() }
valueSelect={ this.getAccountName() }
styleSelect={{ width: '60%' }}
onChange={this.handleSOFChange}
/>
</div>
</div>
)
}
}
export default Form