React: Updating state when state is an array of objects

后端 未结 2 1478
盖世英雄少女心
盖世英雄少女心 2020-12-04 20:14

I have an array of objects in state:

this.state = {
  items: [
    {id: 1, someattr: \"a string\", anotherattr: \"\"},
    {id: 2, someattr: \"another string         


        
2条回答
  •  悲&欢浪女
    2020-12-04 20:40

    If you wish to use a function, this is how I would do it...

    const[array,setArray]= useState([
        {id: 1, value: "aws", othervalue: "was"},
        {id: 2, value: "goo", othervalue: "nano"},
        {id: 3, value: "micro", othervalue: "marcro"},
    ])
    
    const updateItem =(id, whichvalue, newvalue)=> {
        let index = array.findIndex(x=> x.id === id); 
    /*this line is only neccessay if your element's id 
    isn't its postion/index in the array or related to it.
    In the case that it is, use the id as the index, or run the function
    (binary/hash) that relates the id to that position/index to find the index.
    */
        if (index !== -1){
            let temporaryarray = array.slice();
            temporaryarray[index][whichvalue] = newvalue;
            setArray(temporaryarray);
        }
        else {
            console.log('no match');
        }
    }
        /* --longer version--
        var index = array.findIndex(x=> x.id === id);
        let g = array[index]
        g[whichvalue] = newvalue
        if (index === -1){
            console.log('no match')
        }
        else {
            setArray(
                [
                ...array.slice(0,index),
                g,
                ...array.slice(index+1)
                ]
            );
        }
        */
        
    //how to use the function    
    onPress={()=>updateItem(2,'value','John Lemon')}
    onPress={()=>updateItem(1,'othervalue','Stringo Stra')}
    

    The first input of the function is the id of the item.

    The second input of the function is the attribute that you wish to change.

    The third input of the function is the new value for that attribute.

提交回复
热议问题