我正在编写一个程序,在该程序中我发出请求并检索存储在 firebase 实时数据库中的数据,并尝试使用反应上下文或其他方式在本地存储该数据。我注意到在几个控制台日志之后,发出了请求并且成功接收了数据,但它被设置回 null 从而导致我得到的错误。以下是我的数据上下文代码和我称之为报告上下文的特定上下文。
createDataContext.js
export default (reducer, actions, defaultValue) => {
const Context = React.createContext();
const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, defaultValue);
const boundActions = {};
for (let key in actions) {
boundActions[key] = actions[key](dispatch);
}
return (
<Context.Provider value={{ state, ...boundActions }}>
{children}
</Context.Provider>
);
};
return { Context, Provider };
};
报告上下文.js
import createDataContext from "./createDataContext";
import firebase from "firebase";
const reportReducer = (state, action) => {
switch (action.type) {
case "fetch_report":
return { ...state, report: action.payload };
case "fetch_user":
return { ...state, user: action.payload };
case "add_report":
return { ...state, newReport: action.payload };
case "reset":
return { ...state, newReport: "", refresh: false };
default:
return state;
}
};
const fetchReport = (dispatch) => async () => {
firebase.database().ref("Reports/")
.get()
.then((snapshot) => {
dispatch({ type: "fetch_report", payload: snapshot.val() });
});
};
const fetchUser = (dispatch) => async () => {
const userId = firebase.auth().currentUser;
firebase
.database()
.ref("Users/" + userId.uid)
.on("value", (snapshot) => {
console.log(snapshot.val());
dispatch({ type: "fetch_user", payload: snapshot.val() });
});
};
export const { Context, Provider } = createDataContext(
reportReducer,
{
fetchReport,
fetchUser,
},
{ report: [], user: {}, newReport: "", newFile: "" }
);
下面是我如何在ReportScreen.js中调用这些函数
import { NavigationEvents } from "react-navigation";
import { Context as ReportContext } from "../context/ReportContext";
import ListItem from "../components/ListItem";
import MenuHeader from "../components/MenuHeader";
import {
View,
FlatList,
StyleSheet,
TouchableOpacity,
SafeAreaView,
} from "react-native";
import { Icon } from "react-native-elements";
const ReportScreen = ({ navigation }) => {
const { state, fetchReport, fetchUser } = useContext(ReportContext);
return (
<SafeAreaView forceInset={{ top: "always" }} style={styles.container}>
<NavigationEvents onWillFocus={fetchUser} />
<NavigationEvents onWillFocus={fetchReport} />
<MenuHeader user={state.user.profile.nickname} />
<FlatList
data={state.reports}
keyExtractor={(item) => item._id}
renderItem={({ item }) => {
return (
<TouchableOpacity
onPress={() => navigation.navigate("SingleReport", { item })}
>
<ListItem report={item} user={user} />
</TouchableOpacity>
);
}}
/>
<View style={styles.report}>
<TouchableOpacity onPress={() => navigation.navigate("AddReport")}>
<Icon reverse name="addfile" type="antdesign" color={COLORS.ACCENT} />
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
请问我做错了什么可能导致这不是对象错误?