【问题标题】:componentDidMount is not called when select value state updated选择值状态更新时不调用 componentDidMount
【发布时间】:2018-06-14 05:43:38
【问题描述】:

当下拉值不是“--”时,我正在尝试进行异步调用以获取数据。 选择值状态更新时不会调用 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 is not called when select value state updated. 一生只调用一次

标签: javascript reactjs react-native react-redux


【解决方案1】:

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
}

【讨论】:

  • componentDidMount 调用它似乎是多余的
猜你喜欢
  • 2016-03-01
  • 1970-01-01
  • 2018-07-21
  • 2018-03-22
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 2018-07-25
  • 2020-06-01
相关资源
最近更新 更多