我将用户凭据存储在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:无法将类作为函数调用
我假设您了解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并更新它。组件本身不会发生数据提取,一切都在中间件级别处理。