如何修复 TypeError:navigation.setOptions 不是函数
Posted
技术标签:
【中文标题】如何修复 TypeError:navigation.setOptions 不是函数【英文标题】:How to fix TypeError: navigation.setOptions is not a function 【发布时间】:2021-10-07 01:11:54 【问题描述】:我正在尝试为我的应用实现带有玩笑的反应原生测试库。
目前我的组件导航有问题。
当我运行测试时,我遇到了一个错误:
TypeError: navigation.setOptions is not a function
这是我的组件:
const initialState: StateTypes =
toShowAsGridLayout: false,
isLoadingMoreContacts: false
;
export const Main: FC<Props> = ( navigation ) =>
const dispatch = useDispatch();
const data = useSelector((state: RootState) => state.appReducer);
const [state, setState] = useState<StateTypes>(initialState);
useLayoutEffect(() =>
navigation.setOptions(
title: state.isLoadingMoreContacts ? strings.LOADING : strings.ALL_CONTACTS + ' - ' + data.length,
headerRight: () => (
<TouchableOpacity style=styles.changeLayoutButton onPress=changeLayout>
<Text style=styles.changeLayoutText>state.toShowAsGridLayout ? strings.LIST : strings.GRID</Text>
</TouchableOpacity>
)
);
, [state.isLoadingMoreContacts, state.toShowAsGridLayout])
return (
<View style=styles.container>
renderLayout()
</View>
);
;
这是一个路由器:
const SplashStack = createStackNavigator();
const MainStack = createStackNavigator();
export const RootNavigator = () =>
const isDataLoading = useSelector((state: RootState) => state.appReducer);
return (
isDataLoading
? <SplashStack.Navigator>
<SplashStack.Screen name='SplashStack' component=Splash />
</SplashStack.Navigator>
: <MainStack.Navigator>
<MainStack.Screen name='Main' component=Main />
<MainStack.Screen name='ContactDetails' component=ContactDetails />
</MainStack.Navigator>
);
;
还有一个测试本身:
import React from 'react';
import render from '@testing-library/react-native';
import Main from '../Main';
import * as redux from 'react-redux';
import strings from '../../constants/strings';
import mocks from '../../mocks';
describe('dispatch mock', () =>
it('should dispatch mock', () =>
const useDispatchSpy = jest.spyOn(redux, 'useDispatch');
const useSelectorSpy = jest.spyOn(redux, 'useSelector');
const mockDispatchFn = jest.fn();
useDispatchSpy.mockReturnValue(mockDispatchFn);
useSelectorSpy.mockReturnValue( data: mocks );
const getByText = render(<Main navigation=() />);
getByText(strings.ALL_CONTACTS);
);
);
我该如何解决这个错误?我应该将什么传递给导航道具:
const getByText = render(<Main navigation=() />);
【问题讨论】:
【参考方案1】:您需要使用setOptions
方法传递对象。
const getByText = render(<Main navigation=
setOptions: (props: title: string, headerRight: React.FC ) => void
/>);
【讨论】:
以上是关于如何修复 TypeError:navigation.setOptions 不是函数的主要内容,如果未能解决你的问题,请参考以下文章
如何修复 JavaScript 中的“TypeError:无法读取未定义的属性'map'”?
TypeError: undefined is not an object (evaluating 'navigation.navigate') 当 navigation 参数已经嵌套在组件中
如何修复错误 命令引发异常:TypeError: 'Member' object is not iterable
如何修复“TypeError:无法读取未定义的属性 'toString'” |不和谐.js