Skip to main content
Version: 6.x

Redux 集成

在具有 React Navigation 的应用中使用 Redux 非常容易。它基本上与没有 React Navigation 没有什么不同。

¥It is extremely easy to use Redux in an app with React Navigation. It's basically no different than without React Navigation.

import { Provider } from 'react-redux';
import { NavigationContainer } from '@react-navigation/native';

// Render the app container component with the provider around it
export default function App() {
return (
<Provider store={store}>
<NavigationContainer>{/* Screen configuration */}</NavigationContainer>
</Provider>
);
}

请注意,我们将组件封装在 Provider 中,就像我们通常对 react-redux 所做的那样。哒哒!现在请随意在你的应用中使用 connect

¥Notice that we wrap our components in a Provider like we'd normally do with react-redux. Ta da! Now feel free to use connect throughout your app.

options 中使用 connect 的组件

¥Use a component that is connected in options

创建一个组件,将其 connect 存储到存储中,然后在 title 中使用该组件。

¥Create a component, connect it to the store, then use that component in the title.

function Counter({ value }) {
return <Text>Count: {value}</Text>;
}

const CounterContainer = connect((state) => ({ value: state.count }))(Counter);
<Stack.Screen
name="Test"
component={TestScreen}
options={{ title: () => <CounterContainer /> }}
/>

将你关心的状态作为参数传递到屏幕

¥Pass the state you care about as a param to the screen

如果该值预计不会更改,你可以将其作为参数从连接的组件传递到另一个屏幕。

¥If the value isn't expected to change, you can just pass it from a connected component to the other screen as a param.

<Button
title="Go to static counter screen"
onPress={() =>
props.navigation.navigate('StaticCounter', {
count,
})
}
/>
function StaticCounter({ route }) {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>{route.params.count}</Text>
</View>
);
}

所以我们的组件将如下所示:

¥So our component will look like this:

<RootStack.Screen
name="StaticCounter"
component={StaticCounter}
options={({ route }) => ({ title: route.params.count })}
/>

我也可以将导航状态存储在 Redux 中吗?

¥Can I store the navigation state in Redux too?

这不可能。我们不支持它,因为它太容易搬起石头砸自己的脚并减慢/破坏你的应用。

¥This is not possible. We don't support it because it's too easy to shoot yourself in the foot and slow down / break your app.

然而,可以使用 redux-devtools-extension 检查 导航状态 和操作,以及使用 devtools 执行时间旅行调试。

¥However it's possible to use redux-devtools-extension to inspect the navigation state and actions, as well as perform time travel debugging by using the devtools package.