javascript - 如何修复 TypeError:navigation.setOptions 不是函数
问题描述
我正在尝试用我的应用程序开玩笑地实现本机测试库。
现在我的组件导航有问题。
当我运行测试时,我遇到了一个错误:
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={({})} />);
解决方案
您需要使用setOptions
方法传递对象。
const { getByText } = render(<Main navigation={
{
setOptions: (props: { title: string, headerRight: React.FC }) => void
}
} />);
这个答案可能是相关的
推荐阅读
- swift - 如何使用 Swift 在 NSOutlineView 中搜索字符串
- c# - C# 只获取 X 个文件
- flutter - 如何在 Flutter 中重置所有复选框项目和附加到它的数据?
- python - 在 PyCharm/Windows 上安装 tkinter
- php - 如何在 WHERE 子句中创建包含 PHP implode() 方法的 WP 准备语句
- matlab - Matlab 中的 For 循环定义
- typescript - 打字稿:类型变量在某些情况下不进行类型检查
- spring - 在云中进行应用程序轮询时处理重复
- opencv - 我用opencv遇到了一个关于c++的问题
- reactjs - 如何在 Material UI makestyles 中使用媒体查询