Sharing data between components in React

空扰寡人 提交于 2019-12-06 06:19:23

You can use any publish/subscribe events library and then make your components listen to any event you need.

For example:

import React from 'react'
import 'events' from 'eventPublishSubscribeLibrary'

class Component2 extends React.Component {
  constructor (props) {
    super(props)
    this.toggleVisibility = this.toogleVisibility.bind(this)
    this.state = {
      visible = true
    }
  }
  componentDidMount () {
    events.subscribe('clicked-button', this.toogleVisibility)
  }
  toogleVisibility () {
    this.setState({
      visible: !this.state.visible
    })
  }
  render () {
    return visible && (
      <div>content</div>
    )
  }
}

const Component4 = () => (
  <button onClick={events.publish('clicked-button')}>Toggle Visibility</button>
)

You can find in this post by davidwalsh a simple implementation for a Pub/Sub JavaScript Object. Or you can search in npm for some other library.

the "right" way

This is the most simple implementation I can think of and for small projects it is a quick an easy solution that should work.

Anyway, as far as the project will grow a bit you will start to have a lot of actions/reactions between your components. With every new component you'll add it'll get more complicated to track all of these relations between all your components. Here is where it comes handy to have the global state of your application stored in one single place, and that is one of the three principles that redux is based on: the single source of truth.

I think it's perfect time for you to introduce some state to your app. Try Redux, it's awesome.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!