admin管理员组

文章数量:1414614

So I just switched to using stateless functional ponents in React with Redux and I was curious about ponent lifecycle. Initially I had this :

// actions.js

export function fetchUser() {
    return {
        type: 'FETCH_USER_FULFILLED',
        payload: {
            name: 'username',
            career: 'Programmer'
        }
    }
}

Then in the ponent I used a ponentDidMount to fetch the data like so :

// ponent.js

...
ponentDidMount() {
  this.props.fetchUser()
}
...

After switching to stateless functional ponents I now have a container with :

// statelessComponentContainer.js

...
const mapStateToProps = state => {
  return {
    user: fetchUser().payload
  }
}
...

As you can see, currently I am not fetching any data asynchronously. So my question is will this approach cause problems when I start fetching data asynchronously? And also is there a better approach?

I checked out this blog, where they say If your ponents need lifecycle methods, use ES6 classes. Any assistance will be appreciated.

So I just switched to using stateless functional ponents in React with Redux and I was curious about ponent lifecycle. Initially I had this :

// actions.js

export function fetchUser() {
    return {
        type: 'FETCH_USER_FULFILLED',
        payload: {
            name: 'username',
            career: 'Programmer'
        }
    }
}

Then in the ponent I used a ponentDidMount to fetch the data like so :

// ponent.js

...
ponentDidMount() {
  this.props.fetchUser()
}
...

After switching to stateless functional ponents I now have a container with :

// statelessComponentContainer.js

...
const mapStateToProps = state => {
  return {
    user: fetchUser().payload
  }
}
...

As you can see, currently I am not fetching any data asynchronously. So my question is will this approach cause problems when I start fetching data asynchronously? And also is there a better approach?

I checked out this blog, where they say If your ponents need lifecycle methods, use ES6 classes. Any assistance will be appreciated.

Share Improve this question edited Jun 30, 2017 at 20:49 iehrlich 3,5804 gold badges36 silver badges43 bronze badges asked Jun 26, 2017 at 9:19 wmikwmik 7841 gold badge10 silver badges25 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Firstly, don't do what you are trying to to do in mapStateToProps. Redux follows a unidirectional data flow pattern, where by ponent dispatch action, which update state, which changes ponent. You should not expect your action to return the data, but rather expect the store to update with new data.

Following this approach, especially once you are fetching the data asynchronously, means you will have to cater for a state where your data has not loaded yet. There are plenty of questions and tutorials out there for that (even in another answer in this question), so I won't worry to put an example in here for you.

Secondly, wanting to fetch data asynchronously when a ponent mounts is a mon use case. Wanting to write nice functional ponent is a mon desire. Luckily, I have a library that allows you to do both: react-redux-lifecycle.

Now you can write:

import { onComponentDidMount } from 'react-redux-lifecycle'
import { fetchUser } from './actions'

const User = ({ user }) => {
   return // ...
}

cont mapStateToProps = (state) => ({
  user = state.user
})

export default connect(mapStateToProps)(onComponentDidMount(fetchUser)(User))

I have made a few assumptions about your ponent names and store structure, but I hope it is enough to get the idea across. I'm happy to clarify anything for you.

Disclaimer: I am the author of react-redux-lifecycle library.

Don't render any view if there is no data yet. Here is how you do this.

Approach of solving your problem is to return a promise from this.props.fetchUser(). You need to dispatch your action using react-thunk (See examples and information how to setup. It is easy!).

Your fetchUser action should look like this:

export function fetchUser() {
  return (dispatch, getState) => {
      return new Promise(resolve => {
          resolve(dispatch({         
          type: 'FETCH_USER_FULFILLED',
          payload: {
            name: 'username',
            career: 'Programmer'
          }
        }))
      });
  };
}

Then in your Component add to lifecycle method ponentWillMount() following code:

ponentDidMount() {
  this.props.fetchUser()
    .then(() => {
      this.setState({ isLoading: false });
    })
}

Of course your class constructor should have initial state isLoading set to true.

constructor(props) {
  super(props);

  // ...

  this.state({
    isLoading: true
  })
}

Finally in your render() method add a condition. If your request is not yet pleted and we don't have data, print 'data is still loading...' otherwise show <UserProfile /> Component.

render() {
  const { isLoading } = this.state;

  return (
    <div>{ !isLoading ? <UserProfile /> : 'data is still loading...' }</div>
  )
}

本文标签: javascriptReact stateless functional components and component lifecycleStack Overflow