I'm new to redux and a little confused on how to add life cycle functions to existing starter kit.
Any help is appreciated!
import React from 'react'
import classes from './Counter.scss'
export const Counter = (props) => (
.....
)
Counter.propTypes = {
counter: React.PropTypes.number.isRequired,
doubleAsync: React.PropTypes.func.isRequired,
increment: React.PropTypes.func.isRequired
}
// This somehow doesn't work:
Counter.componentDidMount = () => {
console.log("mounted");
}
export default Counter
You'll have convert it to a regular class, since lifecycle methods are not supported on stateless components.
class Counter extends React.Component {
static propTypes = {
}
componentDidMount () {
console.log('mounted!')
}
render () {
// ...
}
}
The reason we've opted for stateless components in the counter example is because we'd like to encourage their usage, primarily because they force you to avoid using any sort of component state.
Hopefully this answers your question. Going to close since it is not an issue with this project, but willing to help more if needed!
Thanks for the answer, David.
If I want to use stateless components.
What is the recommended pattern for calling a function on startup?
Such as Increment(3) on startup in the counter example.
The reason is I wanted to fetch some configuration files from server on startup page.
Thank you for you time.
Awesome project by the way!
This is definitely a common issue. I have two suggestions/techniques for you: 1) Use React Router's onEnter and 2) Use a combination of smart and dumb components. For example, your smart component would just fetch your data and call the dumb/presentational component. Inside the functional/stateless/dumb component you can use the data as a prop. Hope this helps!
BTW, class based components also can be called dumb as long as they don't play with state and can be easily reusable in any other (event not redux based) environment.
It's false thinking that only functional components are dumb, so if you need componentDidMount type of features, go for class based components, everything will be fine ;)
Most helpful comment
You'll have convert it to a regular class, since lifecycle methods are not supported on stateless components.
The reason we've opted for stateless components in the counter example is because we'd like to encourage their usage, primarily because they force you to avoid using any sort of component state.
Hopefully this answers your question. Going to close since it is not an issue with this project, but willing to help more if needed!