Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

reactjs - Initial value set for material ui drop-down passed as prop not being set

I am attempting to create a form which displays units of measurement in a drop-down menu. However, I am trying to set the initial value to a value retrieved from the database, this passed as a prop from another file.

This is a snippet of the Form:

<FormControl>
                <InputLabel>Weight</InputLabel>
                    {checkWeightValueFunction()} 
                    <Select className="weightSelect" name="weight" value={weightValue || ""} onChange={handleWeightChange} >
                                    <MenuItem value={10} >kg</MenuItem>
                                    <MenuItem value={20} >lbs</MenuItem>
                    </Select>
                 </FormControl> 

As can be seen above, I am creating a function called checkWeightValueFunction(). This uses the weight value passed with the prop and sets the weight value accordingly:

   const [weightValue, setWeightValue] = useState("");
         const weightPassed = props.userUnits.weight;
         const checkWeightValueFunction = () => {
             if(checkWeightExecuted==false)
                {
                    switch( props.userUnits.weight)
                    {
                        case "kg": setWeightValue(10); if(weightValue!="") {checkWeightExecuted=true;}   break;
                        case "lbs": setWeightValue(20); if(weightValue!="") {checkWeightExecuted=true;}  break;
                    }
                } 
        }

Currently, my code does not set the default value of the weight. However, if I click on another drop-down list within the same form (did not show this part as it is not related to the issue), the weight is set to the desired value, hence the code works after a change in state is noted.

question from:https://stackoverflow.com/questions/65906488/initial-value-set-for-material-ui-drop-down-passed-as-prop-not-being-set

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issues was related to the userUnits not being set correctly. This is a prop that is being passed from another file.

Previously, userUnits were set using the following code:

var copyOfUnits = unitsFromGet.slice(0);
    userUnits.weight=copyOfUnits.pop()

The proper implementation of the useState is to make use of a setUserUnits which may be used as follows:

setUserUnits(
    {
       weight: copyOfUnits.pop()
     }
   );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...