reactjs - setState doesn't apply changes to component state -


i use react v16.0.0-alpha.6 , react-native v0.44.2.

i've encountered weird situation.

state changed code below. expected result. it's ok.

// current this.state.searchinputvalue 'q'  // coming searchinputvalue 'a'  _handlesearchinputvaluechanged = (searchinputvalue) => {     this.state.searchinputvalue = searchinputvalue     // here searchinputvalue of state 'a' } 

state changed code below. expected result too. it's ok.

// current this.state.searchinputvalue 'q'  // coming searchinputvalue 'a'  _handlesearchinputvaluechanged = (searchinputvalue) => {     settimeout(()=>this.setstate({ searchinputvalue }))     // after running settimeout , async setstate methods     // searchinputvalue of state 'a'  } 

however normal usage of setstate doesn't work

// current this.state.searchinputvalue 'q' // coming searchinputvalue 'a' _handlesearchinputvaluechanged = (searchinputvalue) => {     this.setstate({ searchinputvalue })     // after running async setstate method     // searchinputvalue of state still 'q'  } 

i wonder there chance overcome issue?

edit

i have edited explanation show issue easily. setstate operation doesn't throw error. doesn't change current value of state prop.

in component encountered issue on, 2 eventlisteners , several setstate called depends on works. if setstate methods called on-and-on of them should run correctly, right. setstate function.

for now, have use settimeout(()=>this.setstate({ searchinputvalue })) work around.

and weird issue on react-native encountered far :)

i check react , react-native repos if there issue this. find nothing.

also upgraded react 16.0.0-alpha.12 , react-native 0.46.4. unfortunately issue continues.

the first 2 examples deem "normal" both bad practice.

  1. you should never mutate component's state using direct assignment (ie this.state.* = ...)
  2. setstate asynchronous operation , has no reason/benefit of being wrapped in settimeout call.

if attempting change portion of component state , refill rest of existing values, use alternate definition of function:

_handlesearchinputvaluechanged = (searchinputvalue) => {   this.setstate((prevstate, props) => ({     ...prevstate,     searchinputvalue   })) } 

if trying perform action after setstate can provide callback argument after updater argument. can see example of in setstate documentation. considering setstate asynchronous, need use callback or component's componentdidupdate lifecycle method perform operations on state following update.


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -