Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a React component setState() based on a Redux state change?

Tags:

reactjs

redux

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)
    });
  }
}
like image 794
ffxsam Avatar asked Feb 09 '16 06:02

ffxsam


People also ask

Can I use setState with Redux?

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.

How do I change state in React with setState?

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.

How do you pass a state from one component to another in Redux?

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.

How can the state stored in Redux be updated from a React component?

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.


1 Answers

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)
like image 164
Florent Avatar answered Sep 20 '22 16:09

Florent