如何将Navigation获取的更新值存储到Redux的Reducer中?
Redux存储导航参数实现方案
1. 修正现有代码的问题
你当前的reducer存在状态结构不一致的问题,先调整各文件代码:
reducer.js修正后代码
import { CHANGE_SELECTED_COMPANY } from "../actions/action-constants"; const initialState = { company: "", id: "", }; const changeCompanyReducer = (state = initialState, action) => { switch (action.type) { case CHANGE_SELECTED_COMPANY: // 直接替换顶层的company和id字段,不要额外嵌套 return { ...state, company: action.updatedCompany, id: action.updatedId, }; default: return state; } }; export default changeCompanyReducer;
configure-store.js修正后代码
import { combineReducers, createStore } from 'redux'; import changeCompanyReducer from "./reducers/change-company-reducer"; const rootReducer = combineReducers({changeCompanyReducer}); // 初始化store,可根据需求添加中间件比如redux-thunk const store = createStore(rootReducer); export default store;
2. 在获取导航参数的组件中触发存储
拿到navigation参数的位置,调用dispatch触发action即可,分两种常见组件写法:
函数组件(配合React Redux Hooks)
import { useDispatch } from 'react-redux'; import { changeCompany } from '你的action.js对应路径'; const YourComponent = (props) => { const dispatch = useDispatch(); // 获取导航参数 let id = props.route.params.oved; console.log("id-->",id); let company = props.route.params.company; console.log("company--->",company); // 拿到参数后调用dispatch存到Redux useEffect(() => { // 确保参数存在时再触发 if(id && company) { dispatch(changeCompany(company, id)); } }, [id, company, dispatch]); // 其余组件逻辑 }
类组件(配合connect高阶函数)
import { connect } from 'react-redux'; import { changeCompany } from '你的action.js对应路径'; class YourComponent extends React.Component { componentDidMount() { let id = this.props.route.params.oved; let company = this.props.route.params.company; if(id && company) { this.props.changeCompany(company, id); } } // 其余组件逻辑 } export default connect(null, {changeCompany})(YourComponent);
3. 读取存储的Redux值
需要使用参数时通过useSelector获取即可:
import { useSelector } from 'react-redux'; // 组件内部 const { company, id } = useSelector(state => state.changeCompanyReducer);
内容的提问来源于stack exchange,提问作者Ashish good luck chuck
相关产品推荐
相关产品推荐

