I think I know the answer to this, but just to make sure:
I want a React component to call this.setState()
when the Redux state changes to a certain condition (say, state.dataLoaded === true
). Should I somehow use subscribe
, or is that too low level and I should instead use connect
to map state to props? In which case, I assume something like this would be acceptable:
componentWillReceiveProps(nextProps) {
if (nextProps.dataLoaded) {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(nextProps.posts)
});
}
}
We can accomplish the same features using functional setState, reducers are not exclusive of redux being just pure functions and action creators are also simple object creators describing state changes.
The setState() Method State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.
To pass the state into another component, you can pass it as a prop. Then, inside <ExampleComponent /> , you can access the data as this. props.
The only way to update a state inside a store is to dispatch an action and define a reducer function to perform tasks based on the given actions. Once dispatched, the action goes inside the reducer functions which performs the tasks and return the updated state to the store. This is what Redux is all about.
You definitively should use connect
to do this. When redux's state will change, new props will be generated and will trigger componentWillReceiveProps
.
class MyComp extends React.Component {
componentWillReceiveProps(nextProps) {
if (nextProps.dataLoaded) {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(nextProps.posts)
})
}
}
}
export default connect(
state => ({
dataLoaded: state.someStore.loaded
})
)(MyComp)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With