Question: on using rxjs to update props of a react functional stateless component

Question

on using rxjs to update props of a react functional stateless component

Answers 1
Added at 2016-12-26 22:12
Tags
Question

I thought I could use an observable to send in new props every second and have a react (functional, stateless) component thereby update itself. I am not sure what I am missing here. Here's a jsbin

const propsObs = Rx.Observable.from(['Butler', 'Fritz', 'Dusty', 'Petey'])
const inte = Rx.Observable.interval(1000).take(4)
var props={olddog:'Rusty'}
const propsOverTime = propsObs.zip(inte, (aprop,intx)=>aprop) 
propsOverTime.subscribe((x)=>{
  props={...props, olddog:x}
  console.log(props)
})

const App = (props) =>{
  console.log(props.olddog)
  const getDog=()=>props.olddog
  const thedog = getDog()
  return(
    <div><h4>hello {thedog}</h4></div>)
}
ReactDOM.render(<App {...props}/>, document.getElementById('app'))

The Observable changes props every second, each time creating a new props object. Shouldn't that be enough to force a re-render of the component?

Answers
nr: #1 dodano: 2016-12-27 01:12

A functional React component is just that.. a function. It's not "watching" its own props for changes. Something upstream must call your function to get new JSX. If you have an enclosing component that extends React.Component then you can call setState and pass in new props, or in your case, simply call ReactDOM.render with your updated JSX.

const App = props => {
  const getDog = () => props.olddog
  const thedog = getDog()
  return(
    <div><h4>hello {thedog}</h4></div>
  )
}

propsOverTime.subscribe(x => {
  props = {...props, olddog: x}
  ReactDOM.render(<App {...props}/>, document.getElementById('app'))
})
Source Show
◀ Wstecz