我正在阅读 tutorial关于使用 redux 构建前端登录-注册-身份验证应用程序。我不太确定 protectedTest() 函数在以下代码中如何工作。 据我了解,src/actions/index.js 中的 protectedTest 被调用,它返回一个向服务器发送 http 请求的函数。然而,当我们在 src/component/dashboard.js 中调用 this.props.protectedTest 时,我们为什么期望它与服务器通信(作者声称这就是将会发生的情况),而它只应该创建一个可以完成这项工作的函数?或者我在这里遗漏了什么?
src/actions/index.js
import axios from 'axios';
import { browserHistory } from 'react-router';
import cookie from 'react-cookie';
import { AUTH_USER,
AUTH_ERROR,
UNAUTH_USER,
PROTECTED_TEST } from './types';
const API_URL = 'http://localhost:3000/api';
export function errorHandler(dispatch, error, type) {
let errorMessage = '';
if(error.data.error) {
errorMessage = error.data.error;
} else if(error.data{
errorMessage = error.data;
} else {
errorMessage = error;
}
if(error.status === 401) {
dispatch({
type: type,
payload: 'You are not authorized to do this. Please login and try again.'
});
logoutUser();
} else {
dispatch({
type: type,
payload: errorMessage
});
}
}
export function loginUser({ email, password }) {
return function(dispatch) {
axios.post(`${API_URL}/auth/login`, { email, password })
.then(response => {
cookie.save('token', response.data.token, { path: '/' });
dispatch({ type: AUTH_USER });
window.location.href = CLIENT_ROOT_URL + '/dashboard';
})
.catch((error) => {
errorHandler(dispatch, error.response, AUTH_ERROR)
});
}
}
export function registerUser({ email, firstName, lastName, password }) {
return function(dispatch) {
axios.post(`${API_URL}/auth/register`, { email, firstName, lastName, password })
.then(response => {
cookie.save('token', response.data.token, { path: '/' });
dispatch({ type: AUTH_USER });
window.location.href = CLIENT_ROOT_URL + '/dashboard';
})
.catch((error) => {
errorHandler(dispatch, error.response, AUTH_ERROR)
});
}
}
export function logoutUser() {
return function (dispatch) {
dispatch({ type: UNAUTH_USER });
cookie.remove('token', { path: '/' });
window.location.href = CLIENT_ROOT_URL + '/login';
}
}
export function protectedTest() {
return function(dispatch) {
axios.get(`${API_URL}/protected`, {
headers: { 'Authorization': cookie.load('token') }
})
.then(response => {
dispatch({
type: PROTECTED_TEST,
payload: response.data.content
});
})
.catch((error) => {
errorHandler(dispatch, error.response, AUTH_ERROR)
});
}
}
src/components/dashboard.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../actions';
class Dashboard extends Component {
constructor(props) {
super(props);
this.props.protectedTest();
}
renderContent() {
if(this.props.content) {
return (
<p>{this.props.content}</p>
);
}
}
render() {
return (
<div>
{this.renderContent()}
</div>
);
}
}
function mapStateToProps(state) {
return { content: state.auth.content };
}
export default connect(mapStateToProps, actions)(Dashboard);
最佳答案
how come we expect it to communicate with the server(the authoer claim that's what will happen) when it should only create a funciton that will do the job
原始的 redux 库使用简单的 javascript 对象进行操作,是的。这意味着没有异步操作,因为应用程序需要知道立即执行什么操作。
但是,显然,应用程序通常需要执行一些异步操作,这就是 redux-thunk
的用武之地。
并且它也在教程中使用,请检查“创建index.js并输入以下内容:”部分
// ...
import reduxThunk from 'redux-thunk';
// ...
const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);
const store = createStoreWithMiddleware(reducers);
// ...
Redux thunk 将立即使用调度函数调用任何操作函数,您可以在其中执行一些必要的异步操作。
https://github.com/gaearon/redux-thunk/blob/master/src/index.js#L3
收到一些结果后,您只需使用收到的数据发送一个普通的旧操作。
dispatch({
type: PROTECTED_TEST,
payload: response.data.content
});
这是我找到的有关 redux-thunk 的视频:https://www.youtube.com/watch?v=1QI-UE3-0PU
redux-thunk 存储库在其自述文件中也有很好的描述。
关于javascript react Redux 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47467516/