你好 Stack Overflow 社区!
我正在寻找一个好的实践和实现来等待组件中的分派(dispatch)操作。
我知道 React-Native 和 Redux-Saga 只是说:不要等待,让商店更新,通过选择器,您的 View 将重新呈现。
一切都很好,但是如何处理这样的事情:
onPress = (object) => {
this.props.editObject(object).then(() => { //editObject is an action
NavigationService.navigateTo(otherScreen);
}).catch((error) => {
// Handle and show validation errors
})
}
当然在上面的例子中,这个崩溃了,因为没有then或者catch,因为它是一个action而不是一个promise...那么如何实现这样的流程呢?
我能想到的唯一解决方案是将字符串 navigateTo 传递给操作并在 saga 本身中导航,这根本不干净......
有什么建议吗?
编辑:
我仍然没有找到解决这个问题的好方法,我对 redux-saga 中间件越来越失望。
再举个具体的例子: 我有一个配置文件和图像需要(按顺序)更新,在任何正常的 js 框架中都是
try {
setLoading(true);
await updateProfile(...);
await updateProfileImage(...);
navigate(...)
} catch (e) {
//...
} finally {
setLoading(false);
}
要用 redux-saga 实现这一点,我需要一个新的存储(带有 profileUpdateDone、profileUpdateFailedStatus、profileImageUpdateDone 和 profileImageUpdateFailedStatus)、一个新的 reducer、新的选择器,...
- 做 Action
- 更新商店
- 在 componentDidUpdate 中监听 profileUpdateDone 或 -FailedStatus
- 处理错误或执行第二个操作
- 更新商店
- 在 componentDidUpdate 中监听 updateProfileImageDone 或 -FailedStatus
- 处理错误或导航
商店因为添加了所有废话而变得非常脏。我可以为每个组件引入一个 store、reducer、actions 和 selectors,但我有 58 个组件和 7 个 store 来管理应用程序的全局状态。 65个store,65个reducer,65个selector files等等,看起来是难以管理的……
我一直在绞尽脑汁寻找某种干净的设计模式来解决这个问题。这似乎是任何 JS 框架都应该能够轻松处理的最基本的基本任务,但由于某些原因,在 redux-saga 中却没有。
我是唯一面临这个问题的人吗,还是 redux-saga 只适用于小型应用程序,例如不超过 20 个屏幕?
最佳答案
您可以在 reducer 中存储一个初始状态,比如 isEditObjectDone:false
。
当 reducer 从 action 接收数据时,将其更改为 true
。
并且,在您的屏幕中 componentDidUpdate
或 componentWillReceiveProps
这样做,
if(this.props.isEditObjectDone){
NavigationService.navigateTo(otherScreen);
}
不要忘记将状态映射到 Prop 。
编辑:
让你的行动返回一个promise
,
像这样,
editObject = object => dispatch =>
new Promise((resolve, reject) => {
//your code and dispatch thing
// don't return dispatch instead do this
dispatch({
type: 'something',
...
});
if (something)
resolve(someData);
else
reject(someError);
});
关于React-Native/Redux-传奇 : how to wait for dispatch to finish,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54783347/