javascript - Why isn't my reactJs re-rendering -
i'm tired of model-binding , trying started react whole stateless idea. went through tutorial , seems straightforward enough.
however, in own app confused why component isn't re-rendering on state change. here entirety of app in coffeescript (_
helpers lodash).
mapobject = _.compose _.object, _.map racers = mapobject ['red', 'blue', 'green'], (name) -> [name, (key: name, class: name, position: 0)] advance = (character) -> racers[character].position += 5; console.log character, "position is", racers[character].position view.setstate racers: racers r = react.dom racer = react.createclass getinitialstate: -> @props render: -> r.div (classname: 'racer '+@state.class, style: (left: @state.position)), ""+@state.position racelane = react.createclass render: -> r.li (onclick: _.partial advance, @props.key), racer @props racetrack = react.createclass getinitialstate: -> @props render: -> r.ul (classname: 'lanes'), _.map @state.racers, racelane view = react.rendercomponent (racetrack racers: racers), (document.queryselector '#racetrack')
we have 3 divs in 3 lanes. click on each lane each div supposed move across (the left inline style adjusted).
i define advance method modifies racers object , calls setstate on view root. , position...does not change.
i know i'm on right track, if instead of changing position remove or add racer works should - doesn't re-render 1 level down. doing wrong?
when call setstate
on root racetrack
component trigger redraw , pass new racer positions racer
components via props. however, these new positions end being ignored: when racers first created storing initial position in internal state , rendering racer
components based on internal state, never gets updated.
one quick fix change racers render based on props instead of state.
http://jsbin.com/bilejeyu/1/edit
racer = react.createclass render: -> r.div (classname: 'racer '+@props.class, style: (left: @props.position)), ""+@props.position
wrapping up, think biggest lesson here when working react, should try avoid redundant state. having root component 1 state , use props 1 common pattern.
Comments
Post a Comment