我有2个下拉列表,我需要根据第一个更新第二个下拉列表的值。在页面加载时,我需要根据条件初始化下拉列表的值,如下所示:
const getInitialState= () => {
//defaultSelected has a value if saved in DB, if not then I set the 0 option value in type, based on this value option value will be populated in the dropdown. I get all the values from parent component
let updatedType= defaultSelected !== ""
? defaultType
: Region.RegionType;
console.log('typeeeee', type)
return updatedType;
}
useEffect(() =>{
//Here in options dropdown values object is set based on type selected
let updatedOptions = !_.isEmpty (type)
? "a" //value from db if save
: "b"; //If not 0th value of the object
setOptions(prevOptions => ({
...prevOptions,
["options"]: updatedOptions
}));
},[type]);
const [type, setType] = useState(getInitialState);
const [options, setOptions] = useState('');
const changeCrTypeHandler = (event) =>{
const { name, value } = event.target;
setType(type =>({
...type,
[name]: value}));
}
return (
<>
<select
onChange={changeCrTypeHandler}
style={{ width: "150px" }}
value={!_.isEmpty(type)}
name= "type"
>
{_.map(customMap, (crId) => { //I get this cusomMap from Parent component
return (
<option
id={crId.customType}
value={crId.customType}
key={crId.customType}
>
{crId.customType}
</option>
);
})}
</select>{" "}
<select
onChange={changeCrHashHandler} //second dropdown onchange
style={{ width: "250px" }}
value={crHashId}
name= "options"
>
{_.map(!_.isEmpty(options), (o) => { //This options are created based on type, which is currently not getting set
return (
<option
id={o.customId}
value={o.customId}
key={o.customId}
>
{o.name}
</option>
);
})}
</select>
基于类型值,然后我需要设置选项的值。
但是我的useEffect钩子不会在类型发生变化时被调用。我怎么能在类型发生变化时调用useEffect方法呢?
任何对此的帮助都将不胜感激。
2条答案
按热度按时间nuypyhwy1#
你在定义
setState
之前调用了它。对于初始值,你只需要返回它而不调用setState
。为了让第二个下拉列表的状态依赖于第一个下拉列表的状态,你可以使用useEffect
钩子,如下所示:更新:
在您的
useEffect
中,更改以下内容:改为:
ff29svar2#
使用useState如下:
对于名称,请不要使用setState作为useState的setter函数。因为setState是React中基于类的组件中的另一个方法