从Redux获取正确的Props值

时间:2018-02-11 21:53:00

标签: reactjs react-native redux react-redux redux-thunk

我目前正在使用React Native制作一个登录页面,我使用Redux和Thunk作为我的中间件。在设置某些内容时,我有很多关于从我的行为中获取价值的问题。我有一个登录页面,它调用NodeJS服务器。单击该按钮时,名为“isFetching”的值将变为true,并且页面应显示加载GIF。最后完成后,它应显示用户在成功登录时获得的令牌。

这是我的登录组件

Login.js

import React, { Component } from 'react'
import { TouchableHighlight, View, Text, StyleSheet, TextInput, Image } from 'react-native'

import { connect } from 'react-redux'
import { loginAPI } from '../actions/actions'

class Login extends Component {
  constructor(props){
    super(props);
  }

  render() {

    return (
      <View style={styles.container}>
        <Text>Email</Text>
      <TextInput
          placeholder="Email"
      />

      <Text>Password</Text>
      <TextInput
          placeholder="Password"
      />
        <TouchableHighlight style={styles.button} onPress={this.props.loginAPI("e@e.e", "eeee")}>
          <Text style={styles.buttonText}>Login</Text>
        </TouchableHighlight>
        {
          isFetching && <Image source={require('../images/loading_gif_src.gif')} />
        }
        {
          token ? (<Text>{token}</Text>) : null

        }
      </View>
    );
  }
}

const { token, isFetching} = this.props.user;

styles = StyleSheet.create({
  container: {
    marginTop: 100,
    paddingLeft: 20,
    paddingRight: 20
  },
  text: {
    textAlign: 'center'
  },
  button: {
    height: 60,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#0b7eff'
  },
  buttonText: {
    color: 'white'
  }
})

function mapStateToProps (state) {
  return {
    user: state.user
  }
}

function mapDispatchToProps (dispatch) {
  return {
    loginAPI: (email, password) => dispatch(loginAPI(email, password))
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Login)

现在我遇到的问题是,它一直在说我不能在我的道具上调用undefined。

Action.js

import {
    LOGIN,
    LOGIN_SUCCESS,
    LOGIN_FAILED
} from '../constants/constants'

export function loginAPI(email, password) {
    return (dispatch) => {
        dispatch(userLogin())
        fetch("http://localhost:3000/users/login", {
                method: 'POST',
                headers: new Headers({
                    'Content-Type': 'application/json'
                  }),
                body: JSON.stringify({
                    email: email,
                    password: password,
                }) // <-- Post parameters
            })
            .then(data => data.json())
            .then(json => {
                console.log('json:', json)
                switch(json.success){
                    case true:
                        dispatch(userLoginSuccess(json.token))
                        break;
                    case false:
                        dispatch(userLoginFailed(json.message))
                    break;
                }
            })
            .catch(err => dispatch(userLoginFailed(err)))
    }
}

function userLogin() {
    return {
        type: LOGIN,
    }
}

function userLoginSuccess(token) {
    return {
        type: LOGIN_SUCCESS,
        token,
    }
}

function userLoginFailed() {
    return {
        type: LOGIN_FAILED,
    }
}

user.js (减速机)

import {
  LOGIN,
  LOGIN_SUCCESS,
  LOGIN_FAILED,
  REGISTER,
  REGISTER_SUCCESS,
  REGISTER_FAILED
  } from '../constants/constants'

const initialState = {
  token: "",
  isFetching: false,
  isRegistered: false,
  error: false
}

export default function reducers(state = initialState, action){
  switch (action.type) {
      case LOGIN:
        return {
          ...state,
          isFetching: true,
        }
      case LOGIN_SUCCESS:
        return {
          ...state,
          isFetching: false,
          token: action.token
        }
      case LOGIN_FAILED:
        return {
          ...state,
          isFetching: false,
          error: true
        }
      case REGISTER:
        return{
          ...state,
          isRegistered: false,
          error: false
        }
      case REGISTER_SUCCESS:
        return{
          ...state,
          isRegistered: true,
          error: false
        }
      case REGISTER_FAILED:
        return{
          ...state,
          isRegistered: false,
          error: true
        }  
      default:
        return state
    }
}

如何通过道具正确获取令牌和isFetching的值?

1 个答案:

答案 0 :(得分:1)

提供userisFetchingtoken作为道具:

function mapStateToProps({user, isFetching, token}) {
    return { user, isFetching, token };
}

更新render()组件的Login.js方法以阅读道具:

render() {
    const { isFetching, token } = this.props;

    return (
        <View style={styles.container}>
            <Text>Email</Text>
            <TextInput placeholder="Email" />

            <Text>Password</Text>
            <TextInput placeholder="Password" />

            <TouchableHighlight style={styles.button} onPress={this.props.loginAPI("e@e.e", "eeee")}>
                <Text style={styles.buttonText}>Login</Text>
            </TouchableHighlight>

            {
                isFetching && <Image source={require('../images/loading_gif_src.gif')} />
            }
            {
                token ? (<Text>{token}</Text>) : null
            }
        </View>
    );
}
相关问题