繁体   English   中英

选择值状态更新时未调用componentDidMount

[英]componentDidMount is not called when select value state updated

我正在尝试执行异步调用以在下拉值不是'-'时获取数据。 当选择值状态更新时,未调用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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM