简体   繁体   English

如果 object 已经在 state 中,则不要添加新条目

[英]If object is already in state dont add new entry

Hello my goal is simple yet i find it hard to achieve:您好,我的目标很简单,但我发现很难实现:

I have the following function which is called everytime an user changes one of the fields in my form:我有以下 function ,每次用户更改表单中的一个字段时都会调用它:

const handleChange = (e) => {
    const { value , name , id } = e.target; 
    setFieldValues(prev => ([...prev, {value : value , field: name , project : id}]))   
}

And the form:和形式:

                <div className='simplicate-fields'> 
                    <span>KPI's</span>   
                    <form onSubmit={handleSubmit}>
                        <textarea defaultValue = {project.fieldKpi.value ? project.fieldKpi.value : null}  name={project.fieldKpi.id} id={project.projectId} onChange = {handleChange}></textarea>
                        <textarea defaultValue = {project.fieldContract ? project.fieldContract.value : null}  name={project.fieldContract.id} id={project.projectId} onChange = {handleChange}></textarea>
                        <input type="submit" value="Opslaan"/>
                    </form>   
                </div>

Everytime i change the input value a new object gets added to the array.每次我更改输入值时,都会将新的 object 添加到数组中。 I dont want this,if an object with the the field and project property already exists i simply want to update the value property instead of adding a whole new entry.我不想要这个,如果具有字段和项目属性的 object 已经存在,我只想更新 value 属性而不是添加一个全新的条目。 I find it hard because i cannot mutate the state directly.我觉得很难,因为我不能直接改变 state。

An example:一个例子:

the initial state is just an array [];最初的 state 只是一个数组 [];

if i make a change to my form the state will look like this:如果我对表格进行更改,state 将如下所示:

[{field: 'job' , project : 123 , value : 'e'}]

if i make another change to the same field with the same properties except value this happens:如果我对除值之外具有相同属性的同一字段进行另一次更改,则会发生这种情况:

[{field: 'job' , project : 123 , value : 'e'} , {field: 'job' , project : 123 , value : 'en'}]

What i want is if the project and field are the same just do this:我想要的是如果项目和领域相同,只需这样做:

[{field: 'job' , project : 123 , value : 'en'}]

and if i'd make another change:如果我再做一次改变:

[{field: 'job' , project : 123 , value : 'ent'}]

instead of creating new objects on every keyword i type而不是在我输入的每个关键字上创建新对象

Maybe you should be using an object instead of an array then?也许您应该使用 object 而不是数组?

Then your initial state can be {} and when you change something add its value to the already set object field.然后您的初始 state 可以是 {} 并且当您更改某些内容时,将其值添加到已设置的 object 字段中。 For example the setFieldValues line would look something like this then assuming the name is unique:例如 setFieldValues 行看起来像这样,然后假设name是唯一的:

setFieldValues(prev => ({...prev, name: {value : value , field: name , project : id}}))

If you need the state to be iterable you could also consider using a Map如果您需要 state 可迭代,您也可以考虑使用Map

Try this:尝试这个:

const handleChange = (e) => {
    const { value, name, id } = e.target;
    setFieldValues(prev => {
        const existingIndex = prev.findIndex(el => (el.field === name) && (el.project === id));
        const newFields = [...prev];
        if (existingIndex >= 0) {
            newFields[existingIndex] = { ...newFields[existingIndex], value };
            return newFields;
        }
        newFields.push({ value: value, field: name, project: id });
        return newFields;
    })
}
const handleChange = (e) => {
    const { value , name , id } = e.target; 
    let projects = fieldValues.map(val => val.project);
    if (projects.includes(id) {
         let newFieldValues = [...fieldValues];
         newFieldValues[projects.indexOf(id)] = { value, field: name, project: id }
         setFieldValues(newFieldValues)
         } else {
            setFieldValues(prev => ([...prev, {value, field: name , project : id}]))
  }
}

try something like this:尝试这样的事情:

class inputForm extends React.Component{
constructor(props){
    super(props);
    this.state = { input1: "", input2: "", input3: false };
}

const changeHandler = (name, value) => {
    this.setState({[name]: value});
}

input fields example:输入字段示例:

<Form.Control type="text" name="input1" value={this.state.input1} onChange={(ev)=>this.changeHandler(ev.target.name, ev.target.value)} />
<Form.Control type="text" name="input2" value={this.state.input2} onChange={(ev)=>this.changeHandler(ev.target.name, ev.target.value)} />
<Form.Check name="input3" checked={this.state.input3} onChange={(ev)=>this.changeHandler(ev.target.name, ev.target.checked)} />

I used react-bootstrap components for input fields.我将 react-bootstrap 组件用于输入字段。 Of course the input3 is a checkbox.当然 input3 是一个复选框。

Oh I forgot this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors哦,我忘了这个: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

I used the bracket notation to access the proper state in changeHandler callback我使用括号符号在 changeHandler 回调中访问正确的 state

Try to override object you already set by creating new one each time, so it will override fields that aren't set yet with new values尝试通过每次创建新的来覆盖您已经设置的 object,因此它将使用新值覆盖尚未设置的字段

setFieldValues(prev =>([ 
  Object.assign(prev, {value , field: name , project: id})
]))

If you don't have to keep fields in an array, just do如果您不必将字段保留在数组中,只需执行

setFieldValues(prev => ({...prev, {value, field: name, project: id}})

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

相关问题 添加一个新项目以从入口点外部反应 State - Add A New Item to React State from outside Entry Point Javascript,如何将 object 添加到数组中,如果数组中不存在此 object 的某些属性 - Javascript, how to add an object to an array, if some properties of this object dont already exist in the array 如果状态对象 prop 已经存在,如何删除它,如果不存在,如何添加它? - How to delete state object prop if it already exist and to add it if it not? setState是否可以使用数字键将新条目添加到对象的开头? - Is it possible to setState to add new entry to beginning of object with numbered keys? 如何向现有的json对象添加新属性 - How to add new property to already existing json object 在数组中添加新的 json 对象时,视图不会刷新。 反应本机 - View dont refresh when add a new json object in array. REACT NATIVE 如何在 React 中使用 state 值动态地将新属性添加到文件 object - How to add new Properties to File object in React with state value dynamically 如何在 State Vuex/Vue/Nuxt 中添加新属性 Object - How to Add new Property Object in State Vuex/Vue/Nuxt ReactJS循环通过对象的状态数组并添加新字段 - ReactJS Loop thru state array of object and add new field 如何将新的子键值添加到 React State 对象 - How to add new child key-value to a React State object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM