【问题标题】:React-Native, Redux, useSelector generating error "Invalid hook call"React-Native,Redux,useSelector 生成错误“无效的钩子调用”
【发布时间】:2021-11-04 18:45:48
【问题描述】:

根据之前一篇文章的帮助,我现在使用 React-Native 功能组件和更新的 Redux 挂钩来获取和设置全局 Redux 状态变量。

当我尝试创建一个外部函数(文件“authentication.js”)时,我的问题出现了,该函数试图使用“useSelector”Redux 函数获取存储的变量“username”的值。

它在外部文件“DetailsS​​creen.js”中运行良好,但在其他外部文件“authentication.js”中却失败了,尽管在我未经训练的眼睛看来是相同的代码,但有一些明显的细微差别。

这段代码完美运行:

DetailsS​​creen.js

import React from 'react';
import type { Node } from 'react';
import { Text, View, Button } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';

export const DetailsScreen = ({ route, navigation }) => {
  const syncedDate = useSelector(state => state.projects.syncedDate);
  console.log('DetailsScreen syncedDate: ', syncedDate);

  const dispatch = useDispatch();
  const changeDate = newDate => dispatch({type: "PJS_SET_SYNCEDDATE", payload: newDate});

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Details</Text>
      <Text>SyncedDate: {syncedDate}</Text>
      <Button
        title="SetDate"
        onPress={() => changeDate("10/15/2021")}
      />
    </View>
  );
};

export default DetailsScreen;

但是这段代码会产生错误:“Invalid hook call”

authentication.js

import React from 'react';
import type { Node } from 'react';
import { useSelector } from 'react-redux';

export const authStage_getToken = () => {
    const username = useSelector(state => state.authentication.username);
    const password = 'testingEncoding';

    // Encode the String
    const credentials = base64.encode(username + ':' + password);
    console.log('authStage_getToken encoded credentials:', credentials);

    return credentials;
}

export default authStage_getToken;

启动此功能的其他文件:

LoginScreen.js

import React, {useState} from 'react';
import type { Node } from 'react';
import { StyleSheet, Text, TextInput, View, Button, TouchableOpacity } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { authStage_getToken } from '../processes/authentication';

export const LoginScreen = ({ route, navigation }) => {
  const [username, setUsername] = useState(useSelector(state => state.authentication.username));

  const dispatch = useDispatch();
  const changeLogin = newLogin => dispatch({type: "AUTH_SET_LOGINAUTHENTICATION", payload: newLogin});

  const onButtonPress = () => {
    if (!username || username === '') {
      setValidationError("Username cannot be blank.");
    } else {
      changeLogin({username:username,password:password});
    }

    console.log('Before triggering getToken...');
    const result = authStage_getToken();
    console.log('After triggering getToken, result: ', result);
  }

  return (
    <View style={styles.container}>   
      <View style={styles.inputRow}>
        <TextInput
          style={styles.input}
          placeholder="Username"
          placeholderTextColor="#808080"
          autoFocus={true}
          onChangeText={(text) => setUsername(text)}
          value={username}
        />
      </View>
      <View style={styles.inputRow}>
        <TouchableOpacity
          style={styles.button}
          onPress={() => onButtonPress()}>
          <Text style={styles.buttonText}>Login</Text>
        </TouchableOpacity>
      </View>
    </View>
  );
};

export default LoginScreen;

const styles = StyleSheet.create ({
  container: {
...

【问题讨论】:

  • 可能组件调用不正确,console.log结果不好

标签: react-native react-redux react-hooks


【解决方案1】:

您正在使用 authStage_getToken 函数作为普通的 Javascript 函数,但由于 useSelector,它实际上是一个自定义钩子,因此您需要将其视为 LoginScreen 上的钩子。 如果你将 const result = authStage_getToken() 移动到你的 userName 钩子下,你应该很高兴。 您可以在此处找到有关自定义挂钩的更多信息:https://reactjs.org/docs/hooks-custom.html

【讨论】:

  • Redux 应该允许我从任何地方访问全局状态,对吧?我正在尝试从外部文件“身份验证”中访问 Redux 状态变量的值。我怎么做?上面的代码是我试图做到这一点,我得到一个错误。注意:我试图在该特定位置调用“authStage_getToken()”的原因是因为在“buttonPressed”函数中验证了用户名值之后,我需要继续处理流程,从对 API 的外部调用开始,因此是 getToken 名称。
猜你喜欢
  • 1970-01-01
  • 2021-03-30
  • 2020-02-20
  • 1970-01-01
  • 2021-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多