首页 > 解决方案 > 在没有事件的情况下如何使用参数“COUNTRY_ID”发布到 API

问题描述

这是我的状态

constructor(props){
    super(props)
    this.state = {
      merchants:[],
    }
  }

这是反应生命周期

componentWillMount() {
    return this.setState({
      COUNTRY_ID: this.props.resGet('country_id')
    })
  }

  async componentDidMount(){
    await Api.post('language/merchant', this.state)
    .then((response) => {
      let responseJson = response
      console.log(responseJson)
      if(responseJson.data.STATUS_CODE === '200'){
        this.setState({
          merchants:response.data.DATA
        })
      }
    })
  }

这是带有"merchant []"属性的初始状态,然后"merchant []"将填充请求的结果,该结果将通过参数发布到API "COUNTRY_ID",如何进入"COUNTRY_ID"状态然后我将参数发布" COUNTRY_ID "到API?

标签: javascriptreactjslifecycle

解决方案


ComponentWillMount

被认为是遗留问题,您应该在新代码中避免使用它们。

componentDidMount将在之后render立即执行componentWillMount,因此,如果componentWillMount具有异步函数,则在调用时可能找不到它们的结果componentDidMount

你可以把你有的东西componentWillMount放进去componentDidMount

async componentDidMount(){
  const countryID = this.props.resGet('country_id');

  await Api.post('language/merchant', countryID)
  .then((response) => {
    let responseJson = response
    console.log(responseJson)
    if(responseJson.data.STATUS_CODE === '200'){
      this.setState({
        merchants:response.data.DATA,
        COUNTRY_ID: countryID
      })
    }
  })
}

推荐阅读