简体   繁体   English

React Redux,如何更改状态中的单个元素?

[英]React Redux, how change a single element inside a state?

i have a question for you.. i have an object stored in my redux store, this object contains other object and array of object.. So, i need to update a single field inside this object and mantain the entire object and after i'll make a post request by passing this object.我有一个问题要问你..我有一个对象存储在我的 redux 存储中,这个对象包含其他对象和对象数组..所以,我需要更新这个对象内的一个字段并维护整个对象,然后我'将通过传递此对象发出发布请求。

My object (payload) is:我的对象(有效载荷)是:

{
name: "test",
surname: " test2",
option: [
{
option1: "option1"
}}
]
additionalInfo: {
location: "street"
}

each element are printend in page using input text field, how i can make a function that onchange method selecte the correct field and update it?使用输入文本字段在页面中打印每个元素,我如何制作一个函数,onchange 方法选择正确的字段并更新它?

function policies(state = initialState, action) {
  const { type, payload } = action;

  switch (type) {
    case policiesTypes.SET_POLICY_DETAILS:  
      return { ...state, content: payload };

You have to dispatch the store.你必须派遣商店。 use store.dispatch in onChange written as a function.在 onChange 中使用store.dispatch编写为函数。 This will help you change the store's global state.这将帮助您更改商店的全局状态。 And in the reducer's switch, it is switch(action) and action object holds action.type and action.payload .而在 reducer 的 switch 中,它是switch(action)并且 action 对象持有action.typeaction.payload When you directly pass action type in the switch statement, you might not get results as expected.当您在 switch 语句中直接传递操作类型时,您可能无法获得预期的结果。

eg :例如:
In your Reducer change the switch statement as:在您的 Reducer 中,将 switch 语句更改为:

switch(action){
case "YOUR_ACTION":
  return {...state, ...action.payload};
}      

In your index.js file,在您的 index.js 文件中,

import store from 'react-redux';
...

onChange=(value)=>{
   store.dispatch({type:"YOUR_ACTION",payload:value});
}

This will clear the existing object's values and update the state with the new values that you provide.这将清除现有对象的值并使用您提供的新值更新状态。 And as you are updating onChange, the state might clear all previous keys too, so be cautious while using it onChange.并且当您更新 onChange 时,状态也可能会清除所有以前的键,因此在使用 onChange 时要小心。

Solved from myself:从我自己解决:

case policiesTypes.SET_POLICY_HEADER:
  let content = JSON.parse(JSON.stringify(state.content));
  content.policyHeader = content.policyHeader || {};
  content.policyHeader[action.key] = action.value;
  return { ...state,  content};

and actions:和行动:

const setPolicyHeader = (key, value) => ({type: policiesTypes.SET_POLICY_HEADER, key, value});

and onchange和onchange

onChange={ e => dispatch(actions.setPolicyHeader('localPolicyNumber', e.target.value))}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM