首页 文章

在Redux中存储值

提问于
浏览
3

我正在构建一个React Native应用程序,主要用于验证票证,供事件管理员使用 . 后端由Laravel应用程序提供,该应用程序具有可用的OAuth2服务器 . 我有一个针对该服务器的工作登录,但现在我需要存储访问令牌,请求数据,例如事件,并验证是否匹配给定事件的票证 .

我正在尝试实现Redux来存储访问令牌等 . 我通过操作正确地更新了存储的登录表单,但我无法使用访问令牌 .

这是登录屏幕:

import React, { Component } from 'react';
import { Text, View, TextInput, Button } from 'react-native';
import { connect } from 'react-redux'
import StringifyBody from './../lib/oauth2/StringifyBody'
import { login, storeTokens } from '../redux/actions/auth.js'

class Login extends Component {
  constructor (props) {
      super(props);
      this.state = {
          route: 'Login',
          loading: false,
          email: '',
          password: '',
          accessToken: '',
      };
  }

  handleClick (e) {
    e.preventDefault();

    return new Promise(function(resolve, reject) {
    var data = StringifyBody(this.state.password, this.state.email)

        // XHR settings
        var xhr = new XMLHttpRequest()
        xhr.withCredentials = true

        xhr.onerror = function() {
            reject(Error('There was a network error.'))
        }

        xhr.open("POST", "http://192.168.0.141/oauth/access_token")
        xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded")

        xhr.send(data)

        xhr.onloadend = function() {

            if (xhr.status === 200) {

                var parsedJson = JSON.parse(xhr.response)

                responseArray = []

                for(var i in parsedJson) {
                    responseArray.push([parsedJson [i]])
                }

                // assign values to appropriate variables
                let accessToken = responseArray[0];

                console.log('access token is: ' + accessToken)

                accessToken => this.setState({ access_token: accessToken })

                this.props.tokenStore(this.state.accessToken)  // This doesn't work: "cannot read property 'tokenStore' of undefined"

                resolve(xhr.response)

            } else {
                reject(Error('Whoops! something went wrong. Error: ' + xhr.statusText))
            }
        }
    })
    .done(() => {
        this.props.onLogin(this.state.email, this.state.password); // This works 
    })
}
  render() {

    return (
        <View style={{padding: 20}}>
            <Text style={{fontSize: 27}}>{this.state.route}</Text>
            <TextInput 
                placeholder='Email'
                autoCapitalize='none'
                autoCorrect={false} 
                keyboardType='email-address'
                value={this.state.email} 
                onChangeText={(value) => this.setState({ email: value })} />
            <TextInput 
                placeholder='Password'
                autoCapitalize='none'
                autoCorrect={false} 
                secureTextEntry={true} 
                value={this.state.password} 
                onChangeText={(value) => this.setState({ password: value })} />
            <View style={{margin: 7}}/>
            <Button onPress={(e) => this.handleClick(e)} title={this.state.route}/>
        </View>
    );
}
}

const mapStateToProps = state => {
  return { 
    isLoggedIn: state.auth.isLoggedIn,
    access_token: state.auth.access_token, 
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onLogin: (email, password) => { dispatch(login(email, password)); },
    tokenStore: (accessToken) => { dispatch(storeTokens(accessToken)) },
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);

Redux动作:

export const login = (email, password) => {
  return {
    type: 'LOGIN',
    email: email,
    password: password
  };
};

export const logout = () => {
  return {
    type: 'LOGOUT'
  };
};

export const storeTokens = () => {
  return {
    type: 'STORE_TOKENS',
    access_token: accessToken,
  }
}

最后是减速器:

const defaultState = {
  isLoggedIn: false,
  email: '',
  password: '',
  access_token: '',
};

export default function reducer(state = defaultState, action) {
  switch (action.type) {
    case 'LOGIN': 
        return Object.assign({}, state, { 
            isLoggedIn: true,
            email: action.email,
            password: action.password
        });
    case 'LOGOUT':
        return Object.assign({}, state, { 
            isLoggedIn: false,
            email: '',
            password: ''
        });
    case 'STORE_TOKENS':
        return Object.assign({}, state, {
            access_token: action.accessToken,
        })
    default:
        return state;
  }
}

我也尝试在 componentDidMount() 中将数据传递给 this.props.storeTokens (实际操作),这给了我错误 undefined is not a function (evaluating 'this.props.storeTokens()') componentDidMount Login.js:57:8

我的问题是:如何将我从XHR POST获得的变量存储在redux存储中?为什么没有定义 this.props.tokenStorethis.props.storeToken

1 回答

  • 3

    嘿这是一个由于javascript概念的错误 . 你正在调用this.props.tokenStore(this..state.accessToken)//这不起作用:“无法读取未定义的属性'tokenStore'”

    在使用ES5语法定义的函数内部 . 要么将函数外部的引用存储在某个变量中,然后使用该变量代替此变量 . 另一个选项是定义箭头函数 . 所以将你的函数关键字改为()=>,这应该有效 . 到目前为止,在您的实现中并未指向您正在考虑的组件

相关问题