0

我有 2 个组件,第一个组件是“注册”作为父组件,第二个组件是“UserCountry”,首先我运行“UserCountry”组件并将状态发送到 API 以获取数据“国家列表”,然后我将它设置为 localStorage,稍后我将传递给“Register / parent”组件,如何在“Register”组件中设置状态以添加从“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的值我没有得到

4

0 回答 0