javascript useEffect钩子在属性更改时未被调用

x33g5p2x  于 2023-03-21  发布在  Java
关注(0)|答案(2)|浏览(115)

我有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>{" "}
          &nbsp; &nbsp;&nbsp; &nbsp;
          <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方法呢?
任何对此的帮助都将不胜感激。

nuypyhwy

nuypyhwy1#

你在定义setState之前调用了它。对于初始值,你只需要返回它而不调用setState。为了让第二个下拉列表的状态依赖于第一个下拉列表的状态,你可以使用useEffect钩子,如下所示:

const [firstDropdown, setFirstDropdown] = useState(getInitialState({type:"", options:""}));
const [secondDropdown, setScondDropdown] = useState(0); // you could use whatever initial value you want here
const getInitialState= () => {
  //some logic to get the value in type
  //just return that inital value without calling setState
  
}
// the function inside useEffect runs every time firstDropdown changes
useEffect(()=>{
  // some logic on firstDropdown
  let value = firstDropdown+25
  setScondDropdown(value)
},[firstDropdown]);

更新

在您的useEffect中,更改以下内容:

setOptions(prevOptions => ({
                ...prevOptions,
                ["options"]: updatedOptions 
              }));

改为:

setOptions(updatedOptions)
ff29svar

ff29svar2#

使用useState如下:

const [state, setState] = useState({})
setState((prev) => {
    // do whatever you want to do with the previous state
})

对于名称,请不要使用setState作为useState的setter函数。因为setState是React中基于类的组件中的另一个方法

相关问题