gpt4 book ai didi

javascript - 我应该使用 Redux Saga 进行 React Navigation 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:11:17 25 4
gpt4 key购买 nike

我无法理解如何最好地使用 Redux-SagaReact-Navigation .

来自 Redux-Saga 文档:

redux-saga is a library that aims to make side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better.

The mental model is that a saga is like a separate thread in your application that's solely responsible for side effects.

在 React-Navigation 的 redux 集成部分,它链接到 this example这表明在没有 redux-saga 的情况下使用 Redux。在此示例中,组件直接将操作分派(dispatch)给 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 进行调度,以便操作和 reducer 尽可能保持纯净。不过,对于导航来说,这感觉不必要地复杂。

您认为哪种做法更好?

最佳答案

不确定您是否完全掌握了 sagas 的概念。使用传奇,您可以声明某些操作的副作用,这些副作用可能会派发其他操作。但是您不会改变发送操作的方式。这也与导航无关。导航没有任何副作用,它是使用 reducer 的纯状态操作。当然,某些导航操作可能会触发加载数据的副作用。然后你会在那些有副作用的特定 Action 上使用传奇。但这就像任何其他副作用一样。所以你决定使用 redux saga 应该与你的导航解决方案无关。

一般来说,saga 会对 Action 使用react,触发副作用并可能调度其他 Action 。 reducer 将通过改变状态来对 Action 使用react而没有副作用。

您的替代方案是在您在 Action 创建者中发送 Action 之前处理副作用(就像 redux-thunk 那样)。还有 redux-observable,它具有与 redux saga 类似的模式,但基于 RxJS,并且不使用 redux saga 具有的 elm 模式。

关于javascript - 我应该使用 Redux Saga 进行 React Navigation 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46246093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com