Javascript 从子组件更新状态
我有两个组件,第一个组件是“Register”作为父组件,第二个组件是“UserCountry”,首先我运行“UserCountry”组件并将状态发送到API以获取数据“country list”,然后我将其设置为localStorage,稍后我将其传递到“Register/parent”组件, 如何在“寄存器”组件中设置状态 要添加我从“UserCountry”组件获得的数据 这是我的父组件“寄存器” 这是一个子组件“UserCountry”,我将把从UserCountry组件获得的数据发送到“Register”组件的父状态Javascript 从子组件更新状态,javascript,reactjs,components,state,Javascript,Reactjs,Components,State,我有两个组件,第一个组件是“Register”作为父组件,第二个组件是“UserCountry”,首先我运行“UserCountry”组件并将状态发送到API以获取数据“country list”,然后我将其设置为localStorage,稍后我将其传递到“Register/parent”组件, 如何在“寄存器”组件中设置状态 要添加我从“UserCountry”组件获得的数据 这是我的父组件“寄存器” 这是一个子组件“UserCountry”,我将把从UserCountry组件获得的数据发送到
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])
}
}
所以我希望以后能像这样(父组件)
我已经试过几次了,属性已经成功添加,但是我没有从localStorage获得值您可以通过props将函数设置为UserCountry,并使用可以在父控件中更改状态的参数进行调用,真实的例子是什么?我仍然不明白,仅仅一个月的时间,我试图做出反应,谢谢
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);
}