2017-03-09 42 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的较低级别组件时需要。

相关问题