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
249 views
in Technique[技术] by (71.8m points)

reactjs - React native picker value not updated correctly

I am working in react native and I am using picker as drop down menu

  <Picker
         style={styles.picker}
         selectedValue={selectedsubject}
         onValueChange={(subjectValue) => pickerActivity(subjectValue)}>
          {allsubjects.map((item, index) => {
                            return (<Picker.Item label={item} value={item} key={index} />)
           })}
   </Picker>

onValueChange prop I am calling this function:

const pickerActivity = (val) => {
        setselectedsubject(val)
        console.log("============")
        console.log(val)
        console.log(selectedsubject)
        console.log("============")

    }

so when value selected from menu items I pass selected value to the function pickerActivity in this function I update the status selectedsubject to the passed value and then I console the status and the value, and in the list i have two value let say (value1 and value2), so let's assume I pressed value1, so what happened: it only console log the passed value and for the status it console log empty string as show below:

[Sat Jan 23 2021 19:43:28.899]  LOG      ============
[Sat Jan 23 2021 19:43:28.900]  LOG      value1
[Sat Jan 23 2021 19:43:28.901]  LOG      
[Sat Jan 23 2021 19:43:28.902]  LOG      ============

and second time when I press for example on value2 from dropdown menu, the passed value will be value2 which correct but for the status it will display the previous item selected from menus which value1 as shown below:

[Sat Jan 23 2021 19:43:28.899]  LOG      ============
[Sat Jan 23 2021 19:43:28.900]  LOG      value2
[Sat Jan 23 2021 19:43:28.901]  LOG      value1
[Sat Jan 23 2021 19:43:28.902]  LOG      ============

so the problem is that status doesn't update from first time, and here my status:

const [selectedsubject, setselectedsubject] = useState('')  
question from:https://stackoverflow.com/questions/65858864/react-native-picker-value-not-updated-correctly

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

1 Reply

0 votes
by (71.8m points)

You should define set-state function with capital letter like this.

const [selectedsubject, setSelectedsubject] = useState('');

For now, you are calling console.log before the state updated. To review the updated state, you need to use useEffect, which only fires on state updates:

useEffect(() => {
  console.log(selectedsubject);
})

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

...