i seen 2 ways of doing same thing not sure proper way.
component
import react, {component} 'react'; import {bindactioncreators} 'redux'; import {connect} 'react-redux'; import {selectuser} '../actions/index' class userlist extends component { renderlist() { return this.props.users.map((user) => { return ( <li key={user.id} onclick={() => this.props.selectuser(user)} > {user.first} {user.last} </li> ); }); } render() { return ( <ul> {this.renderlist()} </ul> ); } } // apps state , pass props userlist // > whenever state changes, userlist automatically re-render function mapstatetoprops(state) { return { users: state.users }; } // actions , pass them props to userlist // > userlist has this.props.selectuser function matchdispatchtoprops(dispatch){ return bindactioncreators({selectuser: selectuser}, dispatch); } // don't want return plain userlist (component) anymore, want return smart container // > userlist aware of state , actions export default connect(mapstatetoprops, matchdispatchtoprops)(userlist);
https://github.com/buckyroberts/react-redux-boilerplate
or
import react "react" import { connect } "react-redux" import { fetchuser } "../actions/useractions" import { fetchtweets } "../actions/tweetsactions" @connect((store) => { return { user: store.user.user, userfetched: store.user.fetched, tweets: store.tweets.tweets, }; }) export default class layout extends react.component { componentwillmount() { this.props.dispatch(fetchuser()) } fetchtweets() { this.props.dispatch(fetchtweets()) } render() { const { user, tweets } = this.props; if (!tweets.length) { return <button onclick={this.fetchtweets.bind(this)}>load tweets</button> } const mappedtweets = tweets.map(tweet => <li>{tweet.text}</li>) return <div> <h1>{user.name}</h1> <ul>{mappedtweets}</ul> </div> } }
https://github.com/learncodeacademy/react-js-tutorials/tree/master/5-redux-react
the first way uses 2 different functions mapstatetoprops()
, matchdispatchtoprops()
while other way uses @connect(....).
when use @connect whole bunch of warnings saying has not been finalized , might change.
the @
symbol decorator still considered experimental. use @ own risk. first code block safer way described in official docs. both blocks same thing decorators more sugar anything.
references:
Comments
Post a Comment