反应无状态功能组件和组件生命周期

时间:2017-06-26 09:19:57

标签: javascript reactjs redux react-redux es6-class

所以我只是转而使用 React 中的无状态功能组件 Redux ,我对组件生命周期感到好奇。最初我有这个:

// actions.js

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

然后在组件中我使用componentDidMount来获取数据:

// component.js

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

切换到无状态功能组件后,我现在有一个容器:

// statelessComponentContainer.js

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

如您所见,目前我没有异步获取任何数据。所以我的问题是,当我开始异步获取数据时,这种方法会导致问题吗?还有更好的方法吗?

我查看了这个blog,他们说如果您的组件需要生命周期方法,请使用ES6类。 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

首先,不要在mapStateToProps中执行您要执行的操作。 Redux遵循unidirectional data flow模式,其中通过组件调度操作,更新状态,更改组件。您不应期望您的操作返回数据,而是期望商店使用新数据进行更新。

遵循这种方法,特别是在异步提取数据后,意味着您必须满足尚未加载数据的状态。有很多问题和教程(即使在这个问题的另一个答案中),所以我不会担心在这里为你做一个例子。

其次,想要在组件安装时异步获取数据是一种常见的用例。想要编写好的功能组件是一个共同的愿望。幸运的是,我有一个允许你同时执行这两个工作的库:react-redux-lifecycle

现在你可以写:

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))

我对您的组件名称和商店结构做了一些假设,但我希望它足以让您了解这个想法。我很乐意为你澄清一切。

免责声明:我是react-redux-lifecycle library的作者。

答案 1 :(得分:1)

如果还没有数据,请不要渲染任何视图。这是你如何做到的。

解决问题的方法是从promise返回this.props.fetchUser()。您需要使用react-thunk dispatch您的操作(请参阅示例和信息如何设置。这很简单!)

您的fetchUser操作应如下所示:

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

然后在Component添加到生命周期方法componentWillMount()下面的代码:

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

当然,您的班级constructor应将初始状态isLoading设置为true

constructor(props) {
  super(props);

  // ...

  this.state({
    isLoading: true
  })
}

最后在您的render()方法中添加一个条件。如果您的请求尚未完成且我们没有数据,则打印'数据仍在加载...',否则显示<UserProfile />组件。

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

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