在不接触他人的情况下对 setState 做出反应

react setState without touching others

假设我有如下对象:

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

我想这样做

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 => ... );

顺便问一下,我正在使用 redux ...这对这个有帮助吗?

我在后端使用流明 5.4,res.response.data.params 是 json 对象。

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);

使用Spread运算符:

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

你甚至不需要 forEach。假设响应是这样的 - { currency: 'usd', currency_sign: '$' } - 你可以写

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

它只会影响响应中的值。