我有一个选择语言的选择,当我从选择的语言中获取值/代码时,我将其保存到本地存储中,然后我从我使用的本地存储中获取值/语言代码,并将其作为命中 1 的参数API例如API'pages',根据本地存储中抛出的值/语言代码获取所有语言,成功从API'pages'获得响应后,我将响应存储在本地存储中供我获取和显示根据需要,但为什么当我将本地存储中的数据输入状态时,响应与本地存储不匹配?
constructor(props){
super(props)
this.state = {
language:[],
code:'',
pages:[],
loading:true
};
this.handleChange = this.handleChange.bind(this)
}
handleChange(){
if(this.refs.selectLanguage){
const result = this.refs.selectLanguage.value
this.setState({
code:result
})
this.props.resSave('lang-code', result)
}
//code language from localstorage will send to API 'pages-content'
const getCodeFromLocal = this.props.resGet('lang-code')
Api.post('pages-content', {CODE:getCodeFromLocal})
.then((response) =>{
if(response.data.STATUS_CODE === '200'){
this.props.resSave('toLocalPages' , JSON.stringify(response.data.DATA))
}
})
}
async componentDidMount(){
await Api.get('language')
.then((response) => {
if(response.data.STATUS_CODE === '200'){
this.setState({
language:response.data.DATA,
pages:JSON.parse(this.props.resGet('toLocalPages')),
loading:false
})
}
})
}
render() {
const {language,loading,pages} = this.state
if(loading){
return(
<p>loading...</p>
)
}else{
return (
<React.Fragment>
<Form.Group controlId="selectLanguage">
<Form.Label><b>{this.state.pages.page_login.subtitle}</b></Form.Label>
<Form.Control as="select" ref="selectLanguage" onChange={this.handleChange}>
<option>--select--</option>
{language.map(data => {
return(
<React.Fragment key={data.language_id}>
<option value={data.code}>{data.language_name}</option>
</React.Fragment>
)
})}
</Form.Control>
</Form.Group>
</React.Fragment>
)
}
}
我已经尝试过几次,当我更改语言并检查本地存储时它工作正常,但是当我想要检索要在 UI/ View 中显示的数据时它不起作用,这就是我的方式我做得对吗?
最佳答案
更新:
async componentDidMount(){
let response = await Api.get('language');
let data= await response.json();
this.setState({
language:data,
pages:JSON.parse(this.props.resGet('toLocalPages')),
loading:false
})
}
async handleChange(){
if(this.refs.selectLanguage){
const result = this.refs.selectLanguage.value
this.setState({
code:result,
loading:true;
});
this.props.resSave('lang-code', result)
}
//code language from localstorage will send to API 'pages-content'
const getCodeFromLocal = this.props.resGet('lang-code')
let response = await Api.post('pages-content', {CODE:getCodeFromLocal});
let data= await response.json();
this.props.resSave('toLocalPages' , JSON.stringify(data))
this.setState({
loading:false;
});
}
关于javascript - handleChange 事件与本地存储中的数据不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58296831/