javascript - React Redux 未在 mapStateToProps 中获取状态

标签 javascript react-native react-redux

我试图通过react redux让用户登录我的应用程序,但它给出的错误为

TypeError: undefined is not an object (evaluating 'state.user_name')

app.js

import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import AppDrawer from './drawerNavigator.js';
import  MainNavigator from './screens/stackNavigator'
import { createStore } from 'redux'
import { Provider } from 'react-redux'



  initialState = {
    first_name:"",
    last_name: "",
    user_name: "",
    password: "",  
  }

  const reducer = (state = initialState, action) =>{  
  switch (action.type) {
    case 'SIGN_UP':
    return
       {first_name: state.first_name = action.payload.first_name}        
       {last_name: state.last_name = action.payload.last_name}
       {user_name: state.user_name = action.payload.user_name}         
       {password: state.password = action.payload.password}
      console.log("signUp");
    case 'LOG_IN':
    
    return
     JSON.stringify(action.payload);
  }
  return state
}

const store = createStore(reducer);


export default class App extends React.Component {

constructor(props){
  super(props);  
}

  render() {
    return (
      <>
        <Provider store={store}>
          < MainNavigator/>
        </Provider>

      </>
    );
  }
}

登录.js

import React from 'react';
import { StyleSheet, Text, View, Button, TextInput, Image, TouchableHighlight } from 'react-native';
import { connect } from 'react-redux';
import axios from 'axios';
import { NavigationActions } from 'react-navigation';
import { Actions } from 'react-native-router-flux';


class LogIn extends React.Component {

  
  state = {
    user: "",
    pwd: "",
  } 

  render(){
    const navigation = this.props.navigation;
    return(
      <View style={styles.container}>       
                 
      <View  style={styles.inputContainer}>
      <TextInput style={styles.inputs}
              placeholder="User Name"
              underlineColorAndroid='transparent'
              onChangeText={(text)=>this.setState({user: text})}/>
      </View>          
      <View style={styles.inputContainer}>
      <TextInput style={styles.inputs}
              placeholder="Password"
              secureTextEntry={true}
              underlineColorAndroid='transparent'
              onChangeText={(text)=>this.setState({pwd: text})}/>
      </View>        
      <View style={styles.btn}>
      <TouchableHighlight style={[styles.buttonContainer, styles.loginButton]}  onPress = {()=>this.props.logIn(this.state)}>
         <Text style={styles.loginText}>Login</Text>
      </TouchableHighlight> 

       <TouchableHighlight style={styles.buttonContainer}>
            <Text>Forgot your password?</Text>
        </TouchableHighlight>
                
      <TouchableHighlight style={[styles.buttonContainer, styles.loginButton]} onPress = {()=>navigation.navigate('SignUp')}>  
      <Text>Register here</Text>
        </TouchableHighlight>      
      </View>             
      </View>      
      );
   }
}

const mapStateToProps = (state) =>{
  return {   
    user_name: state.user_name,
    password: state.password
  }
}

const mapDispatchToProps = (dispatch,ownProps) =>{
  return{
    logIn: (text) => {
      if(text.user == ""){
        alert("Enter user name");       
      }
      else if(text.pwd == ""){
        alert("Enter Password");       
      }      
      else {
        var body = {email: text.user,password: text.pwd}
        console.log("body",body);
        axios.post('http://user/login',body)
        .then(res=>{
          console.log("res",res);
             dispatch({ type: 'LOG_IN',payload: res});
             ownProps.navigation.navigate('AppDrawer');
        },err=>{         
             alert(err);         
        }) 
      }      
    }
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(LogIn)

signUp.js

import React from 'react';
import { StyleSheet, Text, View, Button, TextInput, Picker, TouchableOpacity, Image, ScrollView, TouchableHighlight } from 'react-native';
import { AppRegistry } from "react-native";
import { connect } from 'react-redux';
import axios from 'axios';

class SignUp extends React.Component {

 
  state = {
    first_name:"",
    last_name: "",
    user_name: "",
    password: "",
  } 

  render() {

    return (
      <View style={styles.container}>

      <View style={styles.inputContainer}>    
      <TextInput style={styles.inputs}
      placeholder="First Name"
      underlineColorAndroid='transparent'
      onChangeText={(text)=>this.setState({first_name: text})}/>
      </View>

      <View style={styles.inputContainer}>    
      <TextInput style={styles.inputs}
      placeholder="Last Name"
      keyboardType="email-address"
      underlineColorAndroid='transparent' onChangeText={(text)=>this.setState({last_name: text})}/>
      </View>

      <View style={styles.inputContainer}>    
      <TextInput style={styles.inputs}
      placeholder="User Name"              
      underlineColorAndroid='transparent'
      onChangeText={(text)=>this.setState({user_name: text})}/>
      </View>  

      <View style={styles.inputContainer}>    
      <TextInput style={styles.inputs}
      placeholder="Password"              
      underlineColorAndroid='transparent'
      secureTextEntry={true} 
      onChangeText={(text)=>this.setState({password: text})}/>
      </View>

      
      <View style={styles.btn}>
      <TouchableHighlight style={[styles.buttonContainer, styles.loginButton]} onPress={()=>this.props.signUp(this.state)}>
      <Text style={styles.loginText}>Register</Text>
      </TouchableHighlight>                 
      </View>  

      </View>
      );
  }
}


function mapStateToProps (state){
  return {
    first_name: state.first_name,    
    last_name: state.last_name,
    user_name: state.user_name,
    password: state.password,
  }
}



function mapDispatchToProps(dispatch,ownProps){
  return{
    signUp: (text) => {
      if (text.first_name=="") {
        alert("Enter First Name");
      } else if(text.last_name == ""){
        alert("Enter Last Name");       
      }
      else if(text.password == ""){
        alert("Enter Password");       
      }
      else if(text.user_name == ""){
        alert("Enter User_name");       
      }
      else {
        var body = {first_name: text.first_name,last_name: text.last_name,user_name: text.user_name,password: text.password}
        console.log("body",body);
        axios.post('http://user/signup',body)
        .then(res=>{
          dispatch({ type: 'SIGN_UP', payload: body})
          console.log({msg: 'added'});
          ownProps.navigation.navigate('Login')
          },err=>{
          alert(err);
        }) 
      }      
    }
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(SignUp)

错误位于Login.js的mapStateToProps()方法中 我在 App.js 中的状态有 user_name 但它没有在 Login.js 中呈现

最佳答案

您在这里遇到了特定错误。 JS 将评估下面的代码

case 'SIGN_UP':
return
  {first_name: state.first_name = action.payload.first_name}        
  ...

作为

case 'SIGN_UP':
return undefined;
  {first_name: state.first_name = action.payload.first_name}
  ...

这是实例

const testReturn = () => {
  return
    { a: 2 }
}

console.log(testReturn())

当正确放置符号{时效果很好

const testReturn = () => {
  return { 
    a: 2 
  }
}

console.log(testReturn())

与您的 LOG_IN 案例中遇到的问题相同

return
   JSON.stringify(action.payload)

关于javascript - React Redux 未在 mapStateToProps 中获取状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55237963/

相关文章:

Javascript 在 Android 网络浏览器上删除 cookie

android - 如何禁止在 expo/react-native 中使用平板电脑?

node.js - 检测 S3 对象的内容类型/MIME 类型

javascript - 用 Jest 模拟 ES6 类函数

javascript - 是否可以使用 React-strap 构建渐进式 Web 应用程序?

javascript - 可以将JavaScript用作Asp.Net MVC的嵌入式资源吗?

javascript - 从 URL 解码 %20 时出现问题

javascript - 函数中未声明的 JavaScript 变量覆盖了使用

reactjs - 在发布到 npm 之前将 React Native 模块转换为 ES5?

javascript - 终极版 : reset 1 variable to initial state in Redux