当我通常需要链接身份验证操作之类的东西时,我会在connect
ed 登录组件中放入一些逻辑。我会设置一个布尔值,它会在我的redux 操作中从false
变为。并让组件听取该值。当该值更改为 true 时,我将启动第二个操作。true
AUTHENTICATED
例子:
// Auth reducer
export const authentication = (
state = {
authenticated: false,
identity: null,
token: null,
loading: false,
},
action,
) => {
switch (action.type) {
case types.LOGIN:
return {
...state,
};
case types.AUTHENTICATED:
return {
...state,
authenticated: true,
token: action.result.data,
};
case types.LOAD_USER:
return {
...state,
loading: true,
}
case types.LOADED_USER:
return {
...state,
loading: false,
identity: action.result.data
}
default: return state;
}
}
//Connected component:
import { loadUser } from 'actions';
class Login extends React.Component {
componentWillMount() {
const { token, authenticated } = this.props;
if (authenticated && token ) {
// Dispatch your action here;
loadUser(token);
}
}
componentWillReceiveProps(nextProps) {
const { token, authenticated } = nextProps;
const { loadUser } = this.props;
if (authenticated && token ) {
// Dispatch your action here;
loadUser(token);
}
}
...
...
mapStateToProps(state) {
const { token, authenticated } = state.authentication
return {
authenticated,
token
}
}
export default connect(mapStateToProps, { loadUser })(Login)
编辑:如果您宁愿将操作链接在一起,而不是让组件在 redux 存储上侦听以分派操作。看看这里的 redux-thunk 库,它是一个有用的 thunk 中间件,并且有一些非常有用的链接异步操作的示例。