我在名为this.props.onUserLogin的文件中有一个名为Login.js的文件,并传递了用户的身份验证令牌。我可以验证是否通过控制台日志从api调用中获取令牌。当我到达减速器时,我会以某种方式从状态中释放值。我也可以通过控制台日志进行验证。我试图弄清为什么我的state.loginToken在reducer中为空。
Login.js
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main(){
int val1, val2, val3;
cout << "Please enter 3 integers, separated by spaces: ";
cin >> val1 >> val2 >> val3;
int sum = val1 + val2 + val3;
cout << "The sum = " << sum;
double avg = sum / 3.0; // or (val1 + val2 + val3)/3.0
cout << " The average = " << avg << endl;
return 0;
}
reducer.js
import React, {Component} from 'react';
import * as actionTypes from '../Store/actions';
import UserInfoButton from '../UserInfoButton/UserInfoButton';
import { connect } from 'react-redux';
const axios = require('axios');
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
};
}
handleChange = (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
})
}
handleLogin = (event) => {
axios.post('http://127.0.0.1:8000/api/user/token/', {
email: this.state.email,
password: this.state.password,
}).then( (response) => {
console.log('response: ' + response.data.token);
this.props.onUserLogin(response.data.token);
})
.catch( (error) => {
console.log(error)
})
event.preventDefault();
}
render() {
const isLoggedIn = this.props.loginToken;
let userButton;
if(isLoggedIn) {
userButton = <UserInfoButton/>
} else {
userButton = "";
}
return (
<div>
<form onSubmit={this.handleLogin}>
Email:<br/>
<input type="text" value={this.state.email} onChange={this.handleChange} name="email"/><br/>
Password:<br/>
<input type="password" value={this.state.password} onChange={this.handleChange} name="password"/><br/>
<br/>
<input type="submit" value="Submit"></input>
</form>
<div>{this.props.loginToken}</div>
<br/>
<div>{userButton}</div>
</div>
)
}
}
const mapStateToProps = state => {
return {
loginToken: state.loginToken
};
}
const mapDispatchToProps = dispatch => {
return {
onUserLogin: (userToken) => dispatch( { type: actionTypes.USER_LOGIN_ACTION, loginToken: userToken } ),
};
}
export default connect(mapStateToProps,mapDispatchToProps)(Login);
答案 0 :(得分:1)
基本上是减速器中的错字-您正在loginToken
中寻找state
,而不是action
。
case actionTypes.USER_LOGIN_ACTION:
console.log('action: ' + action.loginToken); // not state.loginToken
return {
...state,
loginToken: action.loginToken, // not state.loginToken
}