gpt4 book ai didi

javascript - 当选择值状态更新时,不会调用 componentDidMount

转载 作者:行者123 更新时间:2023-12-01 01:58:03 25 4
gpt4 key购买 nike

当下拉值不是“--”时,我尝试执行异步调用来获取数据。当选择值状态更新时,不会调用 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;

当我们从下拉列表中选择特定值或选项值不是“--”时如何进行异步调用。

最佳答案

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
}

关于javascript - 当选择值状态更新时,不会调用 componentDidMount,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50850368/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com