javascript - 是否可以从 react-native 中的类组件访问功能上下文?
问题描述
我目前正在使用 react-native 项目 v0.63.2 并使用@react-navigation-5。从初始屏幕、登录屏幕和选项卡屏幕导航基于上下文。
appContext.js
import React from 'react';
const AppContext = React.createContext({IsLoading: true, IsLoggedIn: false});
export default AppContext;
导航容器.js
import AppContext from './appContext';
const StackApp = createStackNavigator();
export const StackNavigator = () => {
const [appState, setAppState] = React.useState({});
const state = { appState, setAppState };
React.useEffect(() => {
setAppState({ IsLoading: true, IsLoggedIn: false });
}, []);
return (
<AppContext.Provider value={state}>
{appState.IsLoading ? (
<SplashScreen />
)
: (
<NavigationContainer>
<StackApp.Navigator>
{
appState.IsLoggedIn
?
<>
<StackApp.Screen name='BottomTabScreen' component={BottomTabScreen} options={{ headerShown: false }} />
</>
:
<StackApp.Screen name='LoginScreen' component={NavigatorLogin} options={{ headerShown: false }} />
}
</StackApp.Navigator>
</NavigationContainer>
)}
</AppContext.Provider>
)
}
我使用类组件重新创建新的登录页面。它可以作为功能组件加载所有以前的方式。但我无法修改/更新IsLoggedIn: true
.
我尝试过的: -initLogin.js
import AppContext from '../navigator/appContext';
const AppState = ({ newContext }) => {
const { setAppState } = React.useContext(AppContext);
console.log('setAppState:=> ' + JSON.stringify(setAppState));
console.log('newContext:=> ' + JSON.stringify(newContext));
setAppState(newContext);
}
export class initSignIn extends Component {
onPressLogin = () => {
AppState({ IsLoggedIn: true });
}
}
这将引发错误挂钩规则
无效的挂钩调用。Hooks 只能在函数组件的主体内部调用
我也尝试过使用静态上下文。没有错误,但未定义的值表明密钥IsLoggedIn
不存在。
我的一些参考:
我添加了零食最小脚本。由于我使用的 UI Kitten 主题,可能会出现错误。我不熟悉小吃 Minimal Script
解决方案
这将是一个使用上下文和类组件的工作示例。请记住,当您从一个类访问它时,您只能使用一个上下文。
在这里,我创建了一个可以更新上下文的按钮组件。正如你所看到的,我在上下文中有一个函数,它将更新我们从 useState 传递 setAppState 函数的上下文。
const AppContext = React.createContext({
appState: { IsLoading: true, IsLoggedIn: false },
setAppState: () => {},
});
export default function App() {
const [appState, setAppState] = React.useState({
IsLoading: false,
IsLoggedIn: false,
});
return (
<AppContext.Provider value={{ appState, setAppState }}>
<View style={styles.container}>
<Text style={styles.paragraph}>{JSON.stringify(appState)}</Text>
<Button />
</View>
</AppContext.Provider>
);
}
class Button extends React.PureComponent {
render() {
return (
<TouchableOpacity
onPress={() =>
this.context.setAppState({
IsLoading: !this.context.appState.IsLoading,
IsLoggedIn: true,
})
}>
<Text>Update</Text>
</TouchableOpacity>
);
}
}
Button.contextType = AppContext;
推荐阅读
- nlp - 为什么运行“python run_squad.py”不起作用?
- java - 将 yaml 配置映射到 java hashmap
- excel - Power Query 根据索引添加月份列
- reactjs - 带有反应构建的空白页面
- objective-c - 为什么我看不到 NStextView 的内容
- javascript - Click 事件在 D3 US Map 上不起作用,并且 mouseover 事件仅在特定状态下起作用
- javascript - 在 JS 中增加时间戳 (YYYY-MM-DDTHH:MM:SS) 的问题
- ssis - SSIS:没有足够的存储空间来处理这个命令
- django - django-filter DateTimeFilter 支持带时区的输入吗?
- powershell - 从txt文件中删除BOM并检查删除是否有效