当我通常需要链接认证动作之类的东西时,我在connect
ed登录组件中放置了一些逻辑。我会设置一个布尔值,从false
更改为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-thunk library here,它是一个有用的thunk中间件,并且有一些真正有用的链接异步操作示例。
我以前见过这个建议。只是依靠UI组件来触发基于另一个商店更新的商店更新感觉有点不对。感觉就像属于商店本身或动作创作者一样。 – Graham
它也绝对可以通过动作创作者的链接动作来完成。我更喜欢让自己的行为更加分离,并发现当我以这种方式设置我的应用程序时,动作创建者保持更简洁。我将编辑我的帖子,以便有一个链接在一起的异步操作的例子,但同时在这里有一个很好的讨论例子:https://github.com/reactjs/redux/issues/1676 –
我怀疑重新 - thunk将成为答案。谢谢 :) – Graham