我将用户凭据存储在redux存储中。用户登录时它们已填满。我希望有一种可重用的方法来使用用户名和密码来获取数据。
const initState = {
isLoading: false,
user: undefined,
auth_err: false
};
const fetchData = props => async (url, method, body) => {
try {
const response = await fetch(url, {
method: method,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + Base64.btoa(props.user.username + ":" + props.user.password)
},
body: body
});
console.log(response);
return response;
} catch (err) {
console.log(err);
}
};
const mapStateToProps = state => {
return {
user: state.auth.user
}
};
export const SENDREQUEST = connect(mapStateToProps)(fetchData);
const response = await SENDREQUEST("http://localhost:8080/users", "GET");
但是一旦我叫它,我就会得到:
TypeError:无法将类作为函数调用
答案 0 :(得分:1)
我假设您了解redux及其中间件。
首先,错误来自将fetchData
传递给返回值connect
:connect
返回的函数是HOC:接受一个组件,返回一个此处是class
的组件,无法像您一样调用为函数。
您的问题的一种解决方案是使用mapDispatchToProps
和中间件,大致如下:
class LoginFormPresenter {
render () {
// render your login
return <form onSubmit={this.props.logUser}></form>
}
}
// This makes the LoginFormPresenter always receive a props `logUser`
const LoginFormConnector = connect((state => { user: state.user }), {
logUser: (e) => (
// create a credentials object by reading the form
const credentials = ...;
// return a valid redux action
return {
type: "LOGIN",
credentials
};
)
});
const LoginForm = LoginFormConnector(LoginFormPresenter);
// Create an ad hoc middleware
//
const middleware = ({ dispatch, getState }) => next => action => {
if (action.type === "LOGIN") {
// log your user
fetch()
.then(user => next({ type: "LOGIN", user }));
return next({ type: "PROCESSING_LOGIN" }); // indicate to redux that you are processing the request
}
// let all others actions pass through
return next(action);
};
该机制的工作原理如下:
LoginFormConnector
将把道具logUser
注入到要应用的任何组件中。该道具是一个功能,该功能可使用您的用户凭据调度操作。它还会注入来自redux状态的user
道具,以向用户展示。fetchData
处理请求。解决请求后,您将操作分派给reducer并更新它。组件本身没有数据获取,一切都在中间件级别处理。