我正在try 执行一些条件呈现,所以我创建了一个名为signedIn的布尔值,并try 更改子组件的值.我花了很多时间,大部分价值都是只读的.然后,我找到了一些其他示例,这些示例通过useContext传递了setter函数,并且它在所示的示例上工作,该示例是一个Reaction项目.我的项目是原生react ,我似乎无法触发该函数.我可以读取值,但不能更改它. 我的ConextProvider代码如下:

import React, { useState, useContext } from "react";

const AuthContext = React.createContext();
const AuthUpdateContext = React.createContext();

export function useAuthContext() {
  return useContext(AuthContext);
}

export function useAuthUpdateContext() {
  return useContext(AuthUpdateContext);
}

export function AuthContextProvider({ children }) {
  const [signedIn, setSignedIn] = useState(true);
  function toggleSignedIn() {
    setSignedIn((prevSignedIn) => !prevSignedIn);
    console.log("fired from AuthContextProvider : toggleSignedIn");
    console.log(signedIn);
  }

  return (
    <AuthContext.Provider value={signedIn}>
      <AuthUpdateContext.Provider value={toggleSignedIn}>
        {children}
      </AuthUpdateContext.Provider>
    </AuthContext.Provider>
  );
}

事实上,如果能够通过js setSignedIn(newVal) 来设置SignedInprops 的值会更好,但我也会满足于得到这项工作. 我的Provider 按照许多地方的建议,将应用程序包裹在一起,但功能似乎没有启动. 这就是我在登录屏幕中使用功能的地方

export default function SignInScreen({ navigation }) {
  const [username, setUserName] = useState("");
  const [password, setPassWord] = useState("");
  const signedIn = useAuthContext();
  const toggleSignedIn = useAuthUpdateContext();

  const SignIn = async () => {
    try {
      await login(username, password);
      toggleSignedIn;
      console.log("toggleSignedIn fired from SignInScreen");
      console.log(toggleSignedIn);

推荐答案

您将toggleSignedIn函数作为值传递到AuthContextProvider中,但未将其用作SignInScreen中的函数.你只是简单地引用它,而不是括号.使用函数:

function toggleSignedIn(newVal) {
  setSignedIn(newVal);
}

 const SignIn = async () => {
  try {
    await login(username, password);
    toggleSignedIn(false); // or true, depending on your logic
  } catch (error) {
    // Handle errors
  }
};

React-native相关问答推荐

单击时更改ToucheableOpacity colored颜色 不起作用

RTK 查询显示互联网何时关闭?

react-navigation中的React-native android后退按钮

判断状态对象是否为空

如何将谷歌反向地理编码与 React Native Expo 结合使用?

React-Native 是单线程执行还是多线程执行?

ReactJS toLowerCase 不是一个函数

react native foreach 循环

react-native 链接仅适用于一个项目(Android 或 iOS)

React Native localhost 另一个调试器已经连接

null 不是对象(判断 this.state.count)

React Native:如何获取文件大小、mime 类型和扩展名?

iOS 模拟器如何确认alert信息

如何在自定义组件上使用 onPress?

React-Native:更改 ImageBackground 的不透明度 colored颜色

由于对 sourcetree 的 husky 预推送,Git 推送失败

在react-native中调试应用程序崩溃

React Native:如何将文件拆分为多个文件并导入它们?

react-native-webview :对于 iOS 文本太小

react-navigation 标题有一条微弱的线