简体   繁体   中英

react setState without touching others

Assuming I have an object like below :

person : {
    name : "Test",
    surname : "Test",
    age : 40,
    salary : 5000
    currency : "dollar",
    currency_sign : "$",
    .
    .
    .
}

I want do this

I will send a post request to link like 'update/currency' which currency will be change with many params and I will update the person object with setState but I don't want to touch others which not comes from response.

axios.post('update/currency', {
    currency : 'euro',
    token : '...'
}).then( res => {
    if ( res.response.data.message == 'success' ) {

        res.response.data.params.forEach( (val, index) => {
            // what should i do in here without touching the others
            // forexample params has this props
            // currency
            // currency_sign
            //salary
        });

        // setState to person
        this.setState( ? );
    }
}, err => ... );

by the way I'm using redux ... would it help to this ?

I'm using lumen 5.4 in backend and res.response.data.params is json object.

examle response for res.response.data.params

$params = [
    'currency' => [
        'euro'
    ],
    'currency_sign' => [
        '€'
    ],
    'salary' => '10000',
    'salary_pay' => 'monthly',
    'salary_payment' => [
        ['now'],
        ['check|50%', 'cash|50%']
    ]
];
return response()->json($params);

Use Spread Operator:

this.setState({
  person: {...this.state.person, currency : 'euro'}
})

You don't even need forEach. Assuming that in response will be something like this - { currency: 'usd', currency_sign: '$' } - you can just write

this.setState(person: res.response.data.params);

It will affect only the values what is inside response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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