【发布时间】:2018-02-25 00:44:42
【问题描述】:
我无法理解如何最好地使用 Redux-Saga 和 React-Navigation。
来自 Redux-Saga 文档:
redux-saga 是一个库,旨在使 React/Redux 应用程序中的副作用(即异步操作,如数据获取和不纯操作,如访问浏览器缓存)更容易和更好。
心智模型是,saga 就像应用程序中的一个单独线程,只负责产生副作用。
在 React-Navigation 的 redux 集成部分,它链接到 this example,这表明 Redux 在没有 redux-saga 的情况下使用。在此示例中,组件直接将操作分派给 reducer,而无需中间件。
即
src/components/LoginScreen.js
const LoginScreen = ({ navigation }) => (
<View style={styles.container}>
<Text style={styles.welcome}>
Screen A
</Text>
<Text style={styles.instructions}>
This is great
</Text>
<Button
onPress={() => navigation.dispatch({ type: 'Login' })}
title="Log in"
/>
</View>
);
src/reducers/nav.js
function nav(state = initialNavState, action) {
let nextState;
switch (action.type) {
case 'Login':
nextState = AppNavigator.router.getStateForAction(
NavigationActions.back(),
state
);
break;
case 'Logout':
nextState = AppNavigator.router.getStateForAction(
NavigationActions.navigate({ routeName: 'Login' }),
state
);
break;
default:
nextState = AppNavigator.router.getStateForAction(action, state);
break;
}
// Simply return the original `state` if `nextState` is null or undefined.
return nextState || state;
}
考虑到这一点,我看到了两个选择:
1) 将常规操作(导航等)与引发副作用的操作(异步 api 请求)分开,并且仅将后者与 redux-sagas 一起使用。我认为这需要 connect() 包装器中的 mapDispatchToProps 选项。
2) 要么全部要么什么都不做,并确保所有内容都通过 redux-sagas 进行调度,以便 action 和 reducer 尽可能保持纯净。不过,对于导航来说,这感觉是不必要的复杂。
你认为哪种做法更好?
【问题讨论】:
标签: javascript react-native react-redux react-navigation redux-saga