(React Context API,React Native Expo):在Consumer组件中调用上下文提供的功能

时间:2018-10-19 23:39:50

标签: react-native expo react-context

因此,当我尝试调用状态修改功能时,我什么也没回来。该功能已提供给我在Expo上运行的React Native应用程序中的Consumer组件。这是上下文存储:

authContext.js

const initialState = {
  auth: {
    authenticated: false,
  },
  mode: {
    emergency: false,
  },
};

const authContext = React.createContext();

class AuthProvider extends Component {
  state = {
    ...initialState,
    setAuth: () => { }
  }

  render() {
    return (
      <authContext.Provider value={{ state: this.state }}>
        {this.props.children}
      </authContext.Provider>
    );
  }
}

export {
  authContext, AuthProvider,
};

这是app.js:

App.js

import { AuthProvider } from './src/ContextStore/authContext';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      ...initialState,
      setAuth: this.setAuth
    };
  }

  setAuth = (authenticated) => {
    this.setState((oldState) => ({
      auth: {
        ...oldState.auth,
        authenticated,
      },
    }));
  };

  render() {
    return (
      <AuthProvider>
          <Routes />
      </AuthProvider>
    )
  }
}

这是调用函数setAuth()的组件。它应该将全局状态更新为auth { authenticated : true } ...或至少这就是我想要的状态!然后,这将重定向到新页面。但这根本没有任何作用,在控制台中也没有错误。

Login.js

import { authContext } from '../../ContextStore/authContext';

export default class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: '',
    };
  }

  handleSignIn(email, password) {
    return login(email, password);
  }

  render() {
    return (
      <authContext.Consumer>
        {({ state }) => (
            <Button
              onPress={() => {
                this.handleSignIn(this.state.email, this.state.password)
                  .then((data) => {
                    if (data) {
                      const { setAuth } = state;
                      setAuth(true); // does nothing!
                    } else {
                      console.log('incorrect login details');
                    }
                  });
              }}
              text="Sign in"
            />
        )}
      </authContext.Consumer>
    );
  }
}

这真让我发疯,我已经尽力尝试了我能想到的一切。有任何想法吗?抱歉,如果我发布了太多代码,这是我的新手!

0 个答案:

没有答案