Skip to content

Instantly share code, notes, and snippets.

@DmitryBash
Created April 5, 2020 16:57
Show Gist options
  • Save DmitryBash/113a58e42ee5674f3dfa6363b8776ac5 to your computer and use it in GitHub Desktop.
Save DmitryBash/113a58e42ee5674f3dfa6363b8776ac5 to your computer and use it in GitHub Desktop.
redux-examples-002-dispatch-mapdispatchtoprops
class Profile extends React.Component {
render(props) {
return <div>{props}</div>
}
}
// Dumb component
function Profile(props) {
return <div>{props}</div>
}
// Smart component
// Lambdas aka arrow functions
(a, b) => a + b
x => x*x
x => ({ a: 1, b: 2 }) // returns an object
(a, b) => {
return 123 // function body
}
// almost like
function f() {
}
// Parameters destructuring
const { a, b } = props
Profile({ userName }) => <div>{userName}</div>
const user = { userName: 'xxx', id: 1}
Profile(user)
export default function Profile() {
const Label = () => {
}
return <Label/>
}
// import { createAction } from 'redux-act'
function createEditUser(user) {
// action creator
return {
type: 'EDIT_USER',
payload: user
}
}
function createRefreshUser(id, a, b, c) {
return {
type: 'REFRESH_USER',
payload: { userId: id }
}
}
// const editUser = createAction('Edit user')
//
// dispatch(editUser(new Error()))
// "classic" call
function myMapStateToProps(state) {
return {
fullName: `${state.user.firstName} ${state.user.lastName}`
}
}
function myDispatchStateToProps(dispatch) {
return {}
}
connect(myMapStateToProps, myDispatchStateToProps)
// "modern" call
connect(
// mapStateToProps
state => ({
fullName: `${state.user.firstName} ${state.user.lastName}`
}),
// mapDispatchToProps
dispatch => {
const dispatchRefreshUser = bindActionCreator(createRefreshUser, dispatch)
dispatchRefreshUser(1, 2, 3, 4)
}
)(Profile)
// instead of this
function editUser(user) {
const userAction = createEditUser()
dispatch(userAction)
}
const Profile = ({ fullName, mainColor, userId, refreshUser }) => {
const onClick = () => {
refreshUser(userId)
}
return (
<Fragment>
<div style={`background: ${mainColor}`}>{fullName}</div>
<a onClick={onClick}>Refresh profile</a>
</Fragment>
)
}
// props -> Component -> render
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment