我正在尝试执行异步调用以在下拉值不是' - '时获取数据。 选择值状态更新时不会调用componentDidMount。
const { Fragment } = React;
export class HierarchySelect extends Component {
constructor (props) {
super(props);
this.state = {
department: '',
sections: [],
section: '--'
};
}
componentDidMount () {
if (this.state.section !== '--') {
console.log('inside check');
axios({
method: 'GET',
url: constants.url,
headers: {
'x-access-token': authService.getAccessToken()
}
}).then((res) => {
if (res.status === 200) {
console.log('hulalala', res);
}
})
.catch((err) => { console.log(err); });
}
}
handleChange (value, type, error) {
switch (type) {
case 'section':
this.setState({
section: value,
class: '--'
});
this.props.getClasses({ department: this.state.department, section: value });
break;
default:
}
}
render () {
return (
<Fragment>
<select id="lang" className="department" onChange={e => this.handleChange(e.target.value, 'department')} value={this.state.department}>
{['--', ...this.props.deptHierarchy.data.map(obj => obj.depId).sort((a, b) => a - b)].map(d => <option key={d} value={d}>{d}</option>)}
</select>
<select id="lang" className="section" onChange={e => this.handleChange(e.target.value, 'section')} value={this.state.section}>
{['--', ...this.state.sections].map(d => <option key={d} value={d}>{d}</option>)}
</select>
</Fragment>
);
}
}
export default HierarchySelect;
当我们从下拉列表中选择特定值或选项值不是“ - ”时,如何进行异步调用。
答案 0 :(得分:2)
componentDidMount
在生命中被调用一次。所以,最好将API调用放在一个辅助函数中,并从componentDidMount
和onChange事件中调用它。
doAsyncCall = ()=>{
if (this.state.section !== '--') {
console.log('inside check');
axios({
method: 'GET',
url: constants.url,
headers: {
'x-access-token': authService.getAccessToken()
}
}).then((res) => {
if (res.status === 200) {
console.log('hulalala', res);
}
})
.catch((err) => { console.log(err); });
}
}
componentDidMount () {
this.doAsyncCall();
}
<强> handleChange 强>
handleChange = (value, type, error)=>{
this.setState(()=>{
this.doAsyncCall();
return {
section: value,
class: '--'
};
});
//rest code
}