如何仅用Redux实现React Native两个页面间下拉框选中值传递
Redux跨组件传递下拉框选中值实现方案
1 先确认Reducer层的状态存储逻辑正确
你需要先保证选中值已经被正确存入Redux的Store中:
- 确保
GetDropDownValue的Action定义符合规范,携带选中值作为载荷:
// Action 示例 export const GetDropDownValue = (selectedVal) => { return { type: 'SET_DROPDOWN_SELECTED_VAL', payload: selectedVal } }
- 必须编写对应的Reducer处理该Action,将值存入Store:
// 初始化State const initialState = { dropdownSelectedVal: null } const commonReducer = (state = initialState, action) => { switch(action.type) { case 'SET_DROPDOWN_SELECTED_VAL': return { ...state, dropdownSelectedVal: action.payload } default: return state } } export default commonReducer
- 确认Store配置中已经注册了该Reducer,通过
combineReducers注册时需要明确命名空间:
import { combineReducers, createStore } from 'redux' import commonReducer from './reducers/common' const rootReducer = combineReducers({ common: commonReducer // 此处的common为后续取值的命名空间key }) const store = createStore(rootReducer) export default store
2 确认View1的触发逻辑正常
View1中下拉框选中事件需要正确触发Action传值:
import { connect } from 'react-redux' import { GetDropDownValue } from '../actions' const View1 = (props) => { // 下拉框选中回调 const handleDropDownSelect = (val) => { props.GetDropDownValue(val) } return <ModalDropdown options={你的选项数组} onSelect={handleDropDownSelect} /> } export default connect(null, { GetDropDownValue })(View1)
3 View2取值的实现方案
方案1:通过connect高阶组件取值
通过connect的第一个参数mapStateToProps将Store中的值映射到组件Props即可直接使用:
import { connect } from 'react-redux' const View2 = (props) => { // 直接通过props访问选中值 return <span>当前下拉框选中值:{props.dropdownSelectedVal}</span> } const mapStateToProps = (state) => { return { // state.common对应reducer注册时的命名空间,dropdownSelectedVal是reducer中定义的存储字段 dropdownSelectedVal: state.common.dropdownSelectedVal } } export default connect(mapStateToProps)(View2)
方案2:函数组件使用useSelector Hook取值
如果你的项目使用React Hooks,写法更简洁:
import { useSelector } from 'react-redux' const View2 = () => { const dropdownSelectedVal = useSelector(state => state.common.dropdownSelectedVal) return <span>当前下拉框选中值:{dropdownSelectedVal}</span> }
4 通用问题排查
- 确认入口文件已经用
Provider组件包裹根组件,并且传入了正确的Store实例:
import { Provider } from 'react-redux' import store from './store' import App from './App' ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
- 确认Action的
type字段在定义和Reducer处理时完全一致,无拼写错误
内容的提问来源于stack exchange,提问作者Mondher
相关产品推荐
相关产品推荐

