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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…