跳至主要內容
版本:6.x

Redux 整合

在使用 React Navigation 的應用程式中使用 Redux 非常容易。基本上與不使用 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

選項中使用已 connect 的組件

建立一個元件,將其 連線到儲存庫,然後在 標題中使用該元件。

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 /> }}
/>

將您關心的狀態作為參數傳遞到畫面

如果預計值不會改變,你可以直接將值從連接的元件傳遞到其他畫面作為參數。

<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>
);
}

我們的元件看起來會像這樣

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

我可以將導覽狀態也儲存在 Redux 嗎?

這不可行。我們不支援這麼做,因為這樣很容易造成反效果並讓應用程式變慢或當掉。

不過,你可以使用 redux-devtools-extension 來檢視 導覽狀態 和動作,以及透過使用 devtools 套件 來執行時間旅行除錯。