从子组件更新状态

时间:2019-09-24 07:45:45

标签: javascript reactjs components state

我有2个组件,第一个组件是“ Register”作为父组件,第二个组件是“ UserCountry”,首先运行“ UserCountry”组件并将状态发送到API以获取数据“ country list” ”,然后将其设置为localStorage,稍后将其传递给“注册/父代”组件, 如何在“注册”组件中设置状态 添加从“ UserCountry”组件中获取的数据?

这是我的父组件“注册”

constructor(props){
    super(props)
    this.state = {
      MEMBER_FIRST_NAME:'',
      MEMBER_LAST_NAME:'',
      MEMBER_EMAIL:'',
      MEMBER_PASSWORD:'',
      MEMBER_PASSWORD2:'',
      ACCEPT_MARKETING:1
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e){
    this.setState({
      [e.target.name] : e.target.value
    })
  }

  getIdCountry(){
    return this.setState({
      MEMBER_COUNTRY_ID:localStorage.getItem('country_id'),
      MEMBER_COUNTRY_NAME:localStorage.getItem('country_name'),
    })
  }

  componentDidMount(){
    this.getIdCountry();
  }

  async handleSubmit(e){
    e.preventDefault()
    await Api.post('member/register' , this.state)
    .then((response) => {
      let responJson = response
      console.log(responJson)
    })
  }

这是一个子组件“ UserCountry”,我将从UserCountry组件获取的数据发送到“ Register”组件的父状态。

constructor(props){
    super(props)
    this.state = {
      country: [],
    };
    this.handleSelect = this.handleSelect.bind(this)
  }

  async componentDidMount(){
    await Api.get('user-country', this.state)
    .then((response) => {
      let responseJson = response
      if(responseJson.data.STATUS_CODE === '200'){
        // this.props.resSave('country', JSON.stringify(responseJson.data.DATA))
        this.setState({
          country:response.data.DATA
        })
      }else{
        alert("ERR CONNECTION TIMEOUT")
      }
    })
  }

  handleSelect(e){
    if (this.refs.idCountry) {
      let strResult = this.refs.idCountry.value
      let conToArray = strResult.split(",")
      this.setState({
        MEMBER_COUNTRY_ID:conToArray[0],
        MEMBER_COUNTRY_NAME:conToArray[1]
      })
      this.props.resSave('country_id', conToArray[0])
      this.props.resSave('country_name', conToArray[1])
    }
  }

所以以后我希望像这样(父组件)

constructor(props){
    super(props)
    this.state = {
      MEMBER_FIRST_NAME:'',
      MEMBER_LAST_NAME:'',
      MEMBER_EMAIL:'',
      MEMBER_PASSWORD:'',
      MEMBER_PASSWORD2:'',
      ACCEPT_MARKETING:1,
     // new properties and values ​​obtained from child components
      MEMBER_COUNTRY_ID:localStorage.getItem('country_id'),
      MEMBER_COUNTRY_NAME:localStorage.getItem('country_name'),
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

我尝试了几次,该属性已成功添加,但是我没有从localStorage中获取值

0 个答案:

没有答案