Javascript 在react中存储多个select中的值
我有一个变量,其中包含选择项的数量,这个数字取决于一些API,我想将每个问题的选择存储到localstorage中,因此每次页面重新加载时,选择项都保持不变,我不知道如何做Javascript 在react中存储多个select中的值,javascript,reactjs,Javascript,Reactjs,我有一个变量,其中包含选择项的数量,这个数字取决于一些API,我想将每个问题的选择存储到localstorage中,因此每次页面重新加载时,选择项都保持不变,我不知道如何做 { Object.entries(this.state.liste).map( ([ke,values]) => { let question=ke return ( <div name = &qu
{ Object.entries(this.state.liste).map( ([ke,values]) => {
let question=ke
return (
<div name = "question" >
<h6 className="left">{ke}</h6>
< select className="right" key={values} name = "answer to each question" onChange={(event) =>
this.handleChangeaa(question,event)} >
<option value={this.state.selected} selected disabled hidden onChange={(value)=>
console.log(value)}> Not answered </option>
{Object.values(values).map(key=>{
return (<option key={key.id} id={key}>{key}</option>) })}
</select>
</div>
) })}
{Object.entries(this.state.liste).map([ke,values])=>{
让问题=ke
报税表(
{ke}
在localStorage中,只能将值设置为字符串。您只需在localStorage中为每个具有选定选项的问题插入一些键/值对。在这种情况下,键将是问题的
id
,以及所选选项的值
在您的handlechangea
回调中,您将有如下内容:
handleChangeaa(question, event) {
// Check before if the localStorage is available
localStorage.setItem(question.id, event.target.value);
}
然后,在实例化表单组件时,只需使用localStorage.getItem
函数从localeStorage检索此信息:
componentDidMount() {
// Check if localStorage is available
const stateListCpy = {...this.state.liste}
["question1", "question2"].forEach((questionId) => {
const questionValue = localStorage.getItem(questionId);
if (questionValue) {
const questionIndex = stateListCpy.findIndex((questionBlock) => questionBlock.ke === questionId )
if (questionIndex !== -1) {
stateListCpy[questionIndex].values = questionValue;
}
}
})
this.setState({
liste = stateListCpy;
})
}
然后,您将使用本地存储中的正确值初始化选择
祝你好运 在localStorage中,只能将值设置为字符串。您只需在localStorage中为每个具有选定选项的问题插入一些键/值对。在这种情况下,键将是问题的id
,以及所选选项的值
在您的handlechangea
回调中,您将有如下内容:
handleChangeaa(question, event) {
// Check before if the localStorage is available
localStorage.setItem(question.id, event.target.value);
}
然后,在实例化表单组件时,只需使用localStorage.getItem
函数从localeStorage检索此信息:
componentDidMount() {
// Check if localStorage is available
const stateListCpy = {...this.state.liste}
["question1", "question2"].forEach((questionId) => {
const questionValue = localStorage.getItem(questionId);
if (questionValue) {
const questionIndex = stateListCpy.findIndex((questionBlock) => questionBlock.ke === questionId )
if (questionIndex !== -1) {
stateListCpy[questionIndex].values = questionValue;
}
}
})
this.setState({
liste = stateListCpy;
})
}
然后,您将使用本地存储中的正确值初始化选择
祝你好运