簡體   English   中英

反應無狀態功能組件和組件生命周期

[英]React stateless functional components and component lifecycle

所以我只是轉而使用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
  }
}
...

如您所見,目前我不是異步獲取任何數據。 所以我的問題是,當我開始異步獲取數據時,這種方法會導致問題嗎? 還有更好的方法嗎?

我查看了這個博客 ,他們說如果您的組件需要生命周期方法,請使用ES6類 任何幫助將不勝感激。

首先,不要在mapStateToProps執行您要執行的mapStateToProps Redux遵循單向數據流模式,其中通過組件調度操作,更新狀態,更改組件。 您不應期望您的操作返回數據,而是期望商店使用新數據進行更新。

遵循這種方法,特別是在異步提取數據后,意味着您必須滿足尚未加載數據的狀態。 有很多問題和教程(即使在這個問題的另一個答案中),所以我不會擔心在這里為你舉一個例子。

其次,想要在組件安裝時異步獲取數據是一個常見的用例。 想要編寫好的功能組件是一個共同的願望。 幸運的是,我有一個庫可以讓你做到這兩點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的作者。

如果還沒有數據,請不要渲染任何視圖。 這是你如何做到這一點。

解決問題的方法是從this.props.fetchUser()返回一個promise 您需要使用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 /> Component。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM