React Native Expo:useEffect和setParams不起作用



所以我正在尝试创建一个函数,该函数将传递给我的setParams,这样我就可以通过onPress在导航器中执行该函数中的任何内容。

这是我的编辑产品屏幕:

import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, StyleSheet, TextInput, ScrollView } from 'react-native';
import { useSelector } from 'react-redux';
import { CommonActions } from '@react-navigation/native';
const EditProductScreen = props => {
// Check if you are in edit mode 
const prodId = props.route.params?.productId;
const editedProduct = useSelector(state => state.products.userProducts.find(prod => prod.id === prodId));
const [title, setTitle] = useState(editedProduct ? editedProduct.title : '');
const [imageUrl, setImageUrl] = useState(editedProduct ? editedProduct.imageUrl : '');
const [price, setPrice] = useState('');
const [description, setDescription] = useState(editedProduct ? editedProduct.description : '');

// In order to submit we need to use this handler
const submitHandler = useCallback(() => {
console.log('Submitting!')
});
useEffect(() => {
props.navigation.dispatch(CommonActions.setParams({ submit: submitHandler}));
}, [submitHandler])

正如你在这里看到的:

// In order to submit we need to use this handler
const submitHandler = useCallback(() => {
console.log('Submitting!')
});
useEffect(() => {
props.navigation.dispatch(CommonActions.setParams({ submit: submitHandler}));
}, [submitHandler])

我将此传递到我的setParams,然后在我的导航上:

<AdminNavigator.Screen
name="EditProduct"
component={EditProductScreen}
options={({ route }) => {
// so when you navigate wihout passing anything the route.params is undefined
// when you access a property if undefined it throws an error
const productId = route.params?.productId;
const submit = route.params?.submit;
return {
title: productId ? "Edit Product" : "Add Product",
headerRight: () => (
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
title='Save'
iconName={Platform.OS === 'android' ? 'md-checkmark' : 'ios-checkmark'}
onPress={submit}
/>
</HeaderButtons>
)
};
}}
/>
</AdminNavigator.Navigator>

我正在尝试通过onPress={submit}执行它。但不是console.记录单词";提交";它冻结了屏幕,根本不会移动到任何屏幕。知道是什么原因吗?

问题与导航无关,它在这些行中是

const submitHandler = React.useCallback(() => {
console.log('Submitting!')
});
React.useEffect(() => {
console.log('Submitting! 121');
navigation.setParams({ submit: submitHandler});
}, [])

首先,如果您希望在安装组件时运行useEffect,则不应在此处传递依赖项,问题是当sumbitHandler作为依赖项提供时,它会不断重新呈现,这会导致useCallback创建新的submitHandler,从而导致它最终进入无限循环。此外,也不需要经过常见的操作,您可以直接设置参数,如上所述。

相关内容

  • 没有找到相关文章

最新更新