You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何用Redux将下拉框选中值传递给独立组件

实现方案

步骤1:安装Redux相关依赖

  • 执行安装命令:
    npm install @reduxjs/toolkit react-redux
    若使用yarn可执行:
    yarn add @reduxjs/toolkit react-redux

步骤2:创建选中值的Redux Slice(状态切片)

  • 新建文件src/redux/slices/selectedOptionSlice.js,代码如下:
import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  value: null, // 存储下拉框选中值
}

const selectedOptionSlice = createSlice({
  name: 'selectedOption',
  initialState,
  reducers: {
    setSelectedOption: (state, action) => {
      state.value = action.payload
    },
    clearSelectedOption: (state) => {
      state.value = null
    }
  },
})

// 导出操作方法供组件调用
export const { setSelectedOption, clearSelectedOption } = selectedOptionSlice.actions

// 导出reducer用于注册到store
export default selectedOptionSlice.reducer

步骤3:配置全局Store

  • 新建文件src/redux/store.js,代码如下:
import { configureStore } from '@reduxjs/toolkit'
import selectedOptionReducer from './slices/selectedOptionSlice'

export const store = configureStore({
  reducer: {
    selectedOption: selectedOptionReducer,
    // 其他业务reducer可以在这里追加
  },
})

步骤4:全局挂载Redux Provider

  • 改造App.js,将导航容器包裹在Provider内,确保所有页面组件都能访问Redux状态:
import { Provider } from 'react-redux'
import { store } from './src/redux/store'
import { NavigationContainer } from '@react-navigation/native'
// 导入你自己定义的栈导航器
import YourStackNavigator from './xxx'

export default function App() {
  return (
    <Provider store={store}>
      <NavigationContainer>
        <YourStackNavigator />
      </NavigationContainer>
    </Provider>
  )
}

步骤5:改造SelectDropDown下拉组件

  • 移除组件内部存储选中值的state,选中值改为从Redux获取,选中时同步更新到Redux:
import { useDispatch, useSelector } from 'react-redux'
import { setSelectedOption } from '../redux/slices/selectedOptionSlice'
// 导入你的ModalDropdown组件

const SelectDropDown = () => {
  const dispatch = useDispatch()
  // 从Redux获取当前选中值用于回显
  const selectedValue = useSelector(state => state.selectedOption.value)

  const handleSelect = (value) => {
    // 选中时更新Redux状态
    dispatch(setSelectedOption(value))
  }

  return (
    <ModalDropdown
      defaultValue={selectedValue}
      onSelect={(index, value) => handleSelect(value)}
      // 其他原有配置保持不变
    />
  )
}

export default SelectDropDown

步骤6:任意组件中获取选中值

不管是Screen1下的子组件,还是Screen2下的子组件,都可以直接通过useSelector获取同步的下拉选中值,示例如下:

import { useSelector } from 'react-redux'

// 任意需要使用选中值的组件
const ButtonsGroupe = () => {
  const selectedValue = useSelector(state => state.selectedOption.value)

  // 业务逻辑直接使用selectedValue即可,值会自动同步更新
  return <View>{/* 你的组件内容 */}</View>
}

补充说明

  • 该方案下下拉选中值存在全局Redux中,路由跳转不会丢失数据,所有接入的组件都能拿到最新的选中值
  • 如果需要退出应用后再次打开仍保留选中值,可以额外接入redux-persist实现状态持久化

内容的提问来源于stack exchange,提问作者Mondher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:24:02