【发布时间】:2016-12-06 09:50:33
【问题描述】:
我有一个组件,它使用 componentWillMount 通过 redux 进行 API 调用以获取数据并更新状态。
在调用此方法之前,我需要访问数据库并获取一个属性,我将根据该属性决定是否应该进行数据检索(来自第 1 段)。
我想做什么(使用承诺) -
- 获取属性(来自第 2 段)
- 然后,如果需要数据,则分派正常流程(第 1 段)。
- 如果不需要数据,请继续。
我的问题是您的意见应该放在哪里。
一方面,通过商店来做这件事感觉有点过头了。另一方面,任何机会我都会遇到副作用问题。 此外,我可以在组件或动作创建器中实现逻辑。你认为什么最好?
附加信息: 1.我正在使用redux-thunk。更改为 sagas 是不可能的。 2.我正在检查的属性在1个reducer中,而需要获取的数据在另一个reducer中(不知道,对于某些解决方案可能有问题。)。
选项 1:
import {getData} from '....../dataActions';
import {getToken} from '......../userActions';
const MegaComponent extends React.Component {
componentWillMount() {
getToken(uid)
.then(shouldUpdate => {
if (shouldUpdate) {
getData(uid);
} else {
console.log('no need to get data');
}
})
}
}
funciton mapStateToProps(state, ownProps) {
return {
user: state.user
}
}
function mapDispatchToProps(dispatch) {
return {
getToken: (uid) => dispatch(getToken(uid)),
getData: (uid) => dispatch(getData(uid))
};
}
export default connect(mapStateToProps, mapDispatchToProps)(MegaComponent);
选项2(我认为应该做的)
export function getToken(uid) {
return dispatch => {
return api.getToken(uid)
.then(token => {
if (token === 'what it should') {
return {type: 'NO_DATA_CHANGE_NEEDED', action: null};
} else {
// the action that handle getting data is in a different action creator.
// I either import it here and call it, or there's a better way.
}
})
}
}
更新
这对未来的访客可能会派上用场 - getting state inside an action creator
【问题讨论】:
标签: reactjs redux redux-thunk