简体   繁体   中英

React Native: changing state via external function doesn't rerender

I've created a function as per need to change state only if it's not the same value as before (ie toggle if not same). However, it doesn't rerenders the components. Can someone let me know what I'm doing wrong? It does change the state though.

export function toggleState(thi_s, k, new_v)
{
    if(thi_s.state[k]!=new_v)
    {
        thi_s.state[k] = new_v;
        return true;
    }

    return false;
}

. .

[usage]

if(this.state.xyz!=true) this.setState({xyz:true}); //does rerender as expected

.

toggleState(this, 'xyz', true); //doesn't rerenders 

The state is changed without rerending, and I can check it using console.log right after the call

In toggleState you're not calling setState and are mutating the state directly, which you should never do and is also the reason why a re-render is not triggered:

thi_s.state[k] = new_v;

Change that to

thi_s.setState({[k]: new_v});

Also, instead of passing this to toggleState you should consider using an arrow function or .bind(this) instead so that you can reference this inside of the function w/o passing it as an argument.

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