[Recompose] Create Stream Behaviors to Push Props in React Components with mapPropsStream

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Recompose] Create Stream Behaviors to Push Props in React Components with mapPropsStream相关的知识,希望对你有一定的参考价值。

Rather than using Components to push streams into other Components, mapPropsStream allows you to create functions that can wrap components to create shareable behaviors across components.

 

Using componentFromStream:

import React from "react"
import { render } from "react-dom"
import { Observable } from "rxjs"
import config from "recompose/rxjsObservableConfig"
import {
  setObservableConfig,
  componentFromStream,
  createEventHandler,
  mapPropsStream
} from "recompose"

setObservableConfig(config)
//#endregion

const Counter = props => <h1>{props.count}</h1>

const CounterWithInterval = componentFromStream(
  props$ => props$.switchMap(
    props => Observable.interval(1000),
    (props, count) => ({count, ...props})
  )
  .map(Counter)
)


const App = () => (
  <div>
    <CounterWithInterval />
  </div>
)

render(<App />, document.getElementById("root"))

 

MapPropsStream allows you to create functions that will decorate your component, rather than creating a component itself. I‘m going to create an interval here using MapPropsStream.

A mapProposStream version can be like this:

import React from "react"
import { render } from "react-dom"
import { Observable } from "rxjs"
import config from "recompose/rxjsObservableConfig"
import {
  setObservableConfig,
  componentFromStream,
  createEventHandler,
  mapPropsStream
} from "recompose"

setObservableConfig(config)
//#endregion

const Counter = props => <h1>{props.count}</h1>

const interval = mapPropsStream(props$ => props$.switchMap(
  props => Observable.interval(1000),
  (props, count) => ({ count, ...props })
))

const CounterWithInterval = interval(Counter)


const App = () => (
  <div>
    <CounterWithInterval />
  </div>
)

render(<App />, document.getElementById("root"))

 

As you can see, we take the hightlighted part as own function, wrapped with ‘mapPropsStream‘. 

以上是关于[Recompose] Create Stream Behaviors to Push Props in React Components with mapPropsStream的主要内容,如果未能解决你的问题,请参考以下文章

[Recompose] Lock Props using Recompose -- withProps

[Recompose] Transform Props using Recompose --mapProps

[Recompose] Add Lifecycle Hooks to a Functional Stateless Component using Recompose

[Recompose] Add Local State with Redux-like Reducers using Recompose

[Recompose] Add Local State to a Functional Stateless Component using Recompose

[Recompose] Refactor React Render Props to Streaming Props with RxJS and Recompose