当我运行应用程序时,错误消息显示TypeError: undefined is not an object (evaluating '_useContext.state')
下面是我的App.js:
import React from 'react'
import { StatusBar } from 'expo-status-bar';
import { useState, useEffect, useContext } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Context as ActivitiesContext, Provider } from "./context/ActivitiesContext";
const App = () => {
const { state, getActivity } = useContext(ActivitiesContext);
useEffect(() => {
getActivity()
}, []);
return (
<View style={styles.container}>
<Text>Open App.js to start working on your file</Text>
<StatusBar style="auto" />
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default App
下面是我的ActivitiesContext.js:
import createDataContext from "./CreateDataContext";
const getActivity = () => {
return console.log("hi");
};
export const { Provider, Context } = createDataContext(
{
getActivity,
}
);
下面是我的CreateDataContext.js
import React, { useReducer } from 'react';
export default (reducer, action, defaultValue) => {
const Context = React.createContext();
const Provider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, defaultValue);
const boundActions = {};
for (let key in action) {
boundActions[key] = action[key](dispatch);
}
return (
<Context.Provider value={{ state, ...boundActions }}>
{children}
</Context.Provider>
)
};
return { Context: Context, Provider: Provider };
};
我希望将getActivity
函数中的console.log("hi")
传递给App.js和控制台日志“hi”。
还有提供者,它的目的是什么,我如何使用它?我想这就是我所缺少的。
1条答案
按热度按时间2cmtqfgy1#
1.创建
context
1.使用
Provider
通过 Package 组件来传递值,以提供对树中更深层次组件的访问1.使用
useContext
访问任何组件的值