我假设您了解redux及其中间件。
首先,错误来自传球
fetchData
的返回值
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
应用到任何组件中。这个props是一个函数,它使用用户的凭据来分派操作。它还将注入
user
-
在redux中间件中,您可以捕获操作并使用
获取数据
处理请求。当请求被解决时,您将动作分派给reducer并更新它。组件本身没有数据获取,所有事情都在中间件级别处理。