如何使用navigation.navigate将setter函数(useState)作为prop传递?我将它设置为:
const [firstName, setfirstName] = useState('');
const [dob, setDOB] = useState('');
const [medicalConditions, setMedicalConditions] = useState('');
const [allergies, setAllergies] = useState('');
const [bloodtype, setBloodtype] = useState('');
const [height, setHeight] = useState('');
const [weight, setWeight] = useState('');
return (
<KeyboardAvoidingView style={styles.container} behavior="padding">
<View style={styles.buttonContainer}>
<TouchableOpacity
onPress={() => navigation.navigate('Profile', {
setMedicalConditions: (a) => setMedicalConditions(a),
setAllergies: (b) => setAllergies(b),
setBloodtype: (c) => setBloodtype(c),
setHeight: (d) => setHeight(d),
setWeight: (e) => setWeight(e)
})}
style={[styles.button, styles.buttonOutline]}>
<Text style={styles.buttonText}>Edit</Text>
</TouchableOpacity>
</View>
</View>
</KeyboardAvoidingView>
)
它工作正常,但我得到一个错误说:
Non-serializable values were found in the navigation state. Check:
Profile > params.setMedicalConditions (Function)
This can break usage such as persisting and restoring state. This might
happen if you passed non-serializable values such as function, class
instances etc. in params. If you need to use components with callbacks in
your options, you can use 'navigation.setOptions' instead. See
https://reactnavigation.org/docs/troubleshooting#i-get-the-warning-non-
serializable-values-were-found-in-the-navigation-state for more details.
我尝试使用DeviceEventEmitter,但它表示已弃用。
2条答案
按热度按时间5kgi1eie1#
不能将带有
navigate
的setter函数传递给其他组件你需要做的是创建一个函数来更新你的状态,例如:
现在,您可以传递此函数,并从子组件使用它来更新父组件中的
allergies
状态。3pmvbmvn2#
您必须在屏幕A中创建函数X(包含setter)并传递到屏幕B。当您在屏幕B中调用函数X时,setter也会被调用。
以及
如果只想保存值,请使用**useRef()**insted