问题
Could you please tell me How to add items in select dynamically in react ?
I am getting response from server (name , label etc).For example I just mock my response and after two second I fetch that .
In my example I have two select box or drop down .first dropdown have value “one” and “two”(which is given as options in json).
In json there is one more option dependentField
it mean the field is dependent on another field (value mentioned is dependent).In my example second
field is dependent on first field.
So the value of second select or dropdown field will be ["three", "four"]
if first select box or dropdown value id one
.
So the value of second select or dropdown field will be ["five", "six"]
if first select box or dropdown value id two
.
So I need to watch
the value of field as mention in hook form
https://react-hook-form.com/get-started
Can we dynamically add options
here is code
https://codesandbox.io/s/stoic-benz-lxb8i
useEffect(() => {
console.log("====");
(async () => {
var a = await FETCH_API();
console.log("sssss");
setState(a);
console.log(a);
})();
}, []);
const getForm = () => {
try {
return state.map((i, index) => {
switch (i.type) {
case "text":
return (
<div key={index}>
<label>{i.label}</label>
<input type="text" ref={register()} name={i.name} />
</div>
);
case "select":
if (i.watch) {
watch(i.name, null);
}
return (
<div key={index}>
<label>{i.label}</label>
<select name={i.name} ref={register()}>
{i.options.map((i, idx) => {
return (
<option key={idx} value={i}>
{i}
</option>
);
})}
/
</select>
</div>
);
default:
return <div>ddd</div>;
}
});
return <div>ddd</div>;
} catch (e) {}
};
I don’t wan’t want to do any harcoading like
useEffect(()=>{
},[‘first’])
can we watch or add useeffect dynamically to watch change dynamically ?
Any update
回答1:
this is a simpl two select. Where frist select depend on second
import React,{useState, useEffect} from "react"
const App = () => {
const [state,setState] = useState({
option1:["one","two"],
option2: []
})
useEffect(()=> {
(async () => {
var a = await FETCH_API();
console.log("sssss");
setState({
...state,
option2: a
});
console.log(a);
})();
},[state.option1])
return(
<div>
<select>
{
state.option1.map((i,idx)=>{
return(
<option key={idx} value={i}>
{i}
</option>
)
})
}
</select>
<select>
{
state.option2.map((i,idx)=>{
return(
<option key={idx} value={i}>
{i}
</option>
)
})
}
</select>
</div>
)
}
export default App
来源:https://stackoverflow.com/questions/60261781/how-to-add-items-in-select-dynamically-in-react