Reputation: 418
In my React Native project, I have a small array of objects (always less than 20) with IDs. The ID of the object I need is found in the navigation router, which is not available via Redux selector, I have to get it at the component level. So I am forced to do a little bit of logic. Is it ok for me to be using the constructor
method this way?
class DiscussionScreen extends React.Component {
constructor(props) {
super(props)
// Get discussion data using ID
const discussion = props.discussions.find(
item => item[ID] === props.navigation.getParam(ID)
)
// Pass to state
this.state = {discussion}
}
render() {
return (
<Discussion
discussion={this.state.discussion}
/>
)
}
}
Upvotes: 1
Views: 49
Reputation: 2574
Do you need discussion
in state
? As an alternative to your example, you could do this:
class DiscussionScreen extends React.Component {
_getDiscussion = () => this.props.discussions.find(
item => item[ID] === this.props.navigation.getParam(ID)
)
render() {
return (
<Discussion
discussion={this._getDiscussion}
/>
)
}
}
Upvotes: 1
Reputation: 13
Why don't you use the lifecycle methods to make changes in the state after setting it as empty object in constructor. In my opinion, working with functions in constructor is not good in long runs.
Upvotes: 0