在 redux 中存储更新的值
Posted
技术标签:
【中文标题】在 redux 中存储更新的值【英文标题】:store updated value in redux 【发布时间】:2022-01-06 02:53:08 【问题描述】:我从导航中获得了两个值,即公司和 id。
let id = props.route.params.oved.toString();
console.log("id-->",id);
let company = props.route.params.company.toString();
console.log("company--->",company);
我得到了两个像这样的整数值:--
id-->1
comapny-->465
enter image description here
图片说明:---
如果我在该 textInput 中输入 1 并单击卡片(让我们说第一张卡片 ie465,那么我在导航中得到这两个值,就像我上面提到的整数一样。所以每次我得到更新的值.
我正在从导航中获取更新的值。
所以我想将这些值存储在 redux 中。
action.js:--
import CHANGE_SELECTED_COMPANY from "./action-constants";
export const changeCompany = (updatedCompany, updatedId) =>
return
type: CHANGE_SELECTED_COMPANY,
updatedCompany,
updatedId,
;
;
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:
return
company:
company: action.updatedCompany,
id: action.updatedId,
,
;
return state;
;
export default changeCompanyReducer;
configure-store.js:--
import changeCompanyReducer from "./reducers/change-company-reducer";
const rootReducer = combineReducers(changeCompanyReducer);
如何在 Redux 中存储从导航获取的更新值?
能否请你为 redux 写代码?
【问题讨论】:
请编辑问题以将其限制为具有足够详细信息的特定问题,以确定适当的答案。 【参考方案1】:首先,我建议您像这样编写您的操作:
import CHANGE_SELECTED_COMPANY from "./action-constants";
export const changeCompany = (payload) =>
return
type: CHANGE_SELECTED_COMPANY,
payload // inside payload you can pass: updatedCompany: '...', updatedId: '...'
;
;
然后你需要将你的减速器从你写的改为这个:
import CHANGE_SELECTED_COMPANY from "../actions/action-constants";
const initialState =
company: "",
id: "",
;
const changeCompanyReducer = (state = initialState, action) =>
switch (action.type)
case CHANGE_SELECTED_COMPANY:
const updatedCompany, updatedId = action.payload;
// notice the changes I made in the return statment.
return
...state,
company: updatedCompany,
id: updatedId
;
// you can return the state here
default:
return state;
;
export default changeCompanyReducer;
【讨论】:
以上是关于在 redux 中存储更新的值的主要内容,如果未能解决你的问题,请参考以下文章