2017-03-09 28 views
1

這裏有一個例子:如何以正確的方式使用調度?

export const fetchPosts = (path, postData) => { 
    let url = target + path + Tool.paramType(postData); 
    return dispatch => { 
     dispatch(requestPosts(postData)); 
     return fetch(url,{ 
      mode: 'cors', 
      "Content-Type": "application/json", 
     }) 
     .then(response => { 
      if(response.ok){ 
       response.json().then(json => dispatch(receivePosts(path, json))) 
      }else{ 
       console.log("status", response.status); 
      } 
     }) 
     .catch(error => console.log(error)) 
    } 
} 
時,我想請我的commponent數據

:但是

this.props.fetchPosts(this.props.seting.url,this.props.seting.data) 

,當我輸入這樣的:

import *as action from '../../Redux/Action/Index'; 
action.fetchPosts(this.props.seting.url,this.props.seting.data) 

項目似乎開始成功......是嗎?..... =。=

+0

這有什麼意義?您將動作映射到容器組件中的道具。你爲什麼要這樣做呢? –

+0

簡而言之,第一種方法是正確的 - 不要在所有組件中單獨導入動作。那不建議 –

+0

當我嘗試第二種方法時,似乎沒有錯誤,現在我知道缺點,thx分享@Arshabh Agarwal –

回答

1

爲了使fetchPosts可爲道具,以你的組件,你需要使用mapDispatchToProps功能和bindActionCreators

import *as action from '../../Redux/Action/Index'; 

...... 
mapDispatchToProps(dispatch) { 
    return { 
      fetchPosts: bindActionCreators(action.fetchPosts, dispatch); 
    } 

} 

你也需要從終極版使用connect綁定操作的組件就像

export default connect(null, mapDispatchToProps)(componentName); 

這是正確的方法。

0
import { connect } from 'react-redux' 
    import { 
    requestPosts, 
    receivePosts 
    } from '../../Redux/Action/Index'; 

    export const fetchPosts = (path, postData) => {  
    const url = target + path + Tool.paramType(dispatch(requestPosts(postData))); 
    const { dispatch } = props 

    return fetch(url, { 
     mode: 'cors', 
     "Content-Type": "application/json", 
    }) 
    .then(response => { 
     if(response.ok){ 
      response.json().then(json => dispatch(receivePosts(path, json))) 
     }else{ 
      console.log("status", response.status); 
     } 
    }) 
    .catch(error => console.log(error)) 
} 

export default connect(componentName); 

當您使用connectdispatch將自動成爲props可用,因此您可以將其包含在你的道具的解構直接調用它。看起來在你的代碼中,你已經在Tool.paramType之前通過了postData,並且在返回之後才定義它 - 我不能說這不起作用或者不行,它看起來像是可能是失敗 - 所以我將該調度直接移動到需要數據的地方當需要時。我上面的答案也是正確的,這些只是使用調度的不同方式,我做了兩個 - 最近我停止使用mapDispatchToProps,一旦我知道它已經通過connect道具已經可用,除非我需要bindActionCreators,這是當您將調度傳遞到不知道使用redux的較低級別組件時需要。

相關問題