【发布时间】:2020-08-01 13:38:34
【问题描述】:
https://reactjs.org/docs/hooks-custom.html 构建自己的 Hooks 可以让您将组件逻辑提取到可重用的函数中。 这就是我想要做的:将我的组件逻辑提取到其他组件的可重用函数中。
我的功能组件:
//React
import React from 'react';
import { FlatList, View, Text, StyleSheet } from 'react-native';
//Local
import UserPreview from './UserPreview';
import defaultContainer from '../../shared/styles/defaultContainer';
import useFetchUsers from './../../../handler/useFetchUsers';
export default function UserList(props) {
const { users } = props;
const dispatch = useDispatch();
//State
const [isLoading, setIsLoading] = React.useState(false);
const [error, setError] = React.useState(null);
return (
<View style={defaultContainer}>
<FlatList
data={users}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <UserPreview user={item} />}
ListEmptyComponent={() => <Text style={styles.listEmpty}>Keine Benutzer gefunden!</Text>}
ItemSeparatorComponent={() => <View style={styles.listSeperator} />}
onRefresh={useFetchUsers}
refreshing={isLoading}
contentContainerStyle={styles.container}
/>
</View>
);
}
我的可重用函数:
import React from 'react';
import * as userActions from '../store/actions/user';
import { useDispatch } from 'react-redux';
export default async function useFetchUsers() {
const [error, setError] = React.useState(null);
const dispatch = useDispatch();
const [isLoading, setIsLoading] = React.useState(false);
console.log('StartupScreen: User laden');
setIsLoading(true);
setError(null);
try {
await dispatch(userActions.fetchUsers());
console.log('StartupScreen: User erfolgreich geladen');
} catch (err) {
setError(err.message);
}
setIsLoading(false);
}
【问题讨论】:
标签: reactjs react-native react-hooks