账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    react+redux,异步请求为什么要写在action creator里面?
    • 2017-10-07 00:00
    • 11
    28
    0

    在redux官方文档里面,针对异步给出的方案是:

    export function fetchPosts(subreddit) {
      return function (dispatch) {
        dispatch(requestPosts(subreddit));//准备发起请求
        return fetch(`http://www.subreddit.com/r/${subreddit}.json`)
          .then(response => response.json())
          .then(json => dispatch(receivePosts(subreddit, json)))//拿到请求结果
      }
    }

    主要思路是:

    1. 这是一个特殊的action creator(返回了一个function)
    2. 在这个action creator里面,可以dispatch其他action
    3. 通过redux-thunk中间件,可以dispatch(fetchPosts('sth'))

    为什么异步请求不能直接写在容器组件的mapDispatchToProps里面?

    const mapDispatchToProps = dispatch => ({
        fetchTest: () => {
            dispatch(fetch_request());//准备发起请求
            fetch('/package.json')
                .then(response => response.json())
                .then(json => dispatch(fetch_success(json)))//拿到请求结果
        }
    });
    
    @connect(mapStateToProps, mapDispatchToProps)
    export default class MyContainer extends Component {
        render() {
            return (
                <div>
                    <UIList />
                    <FetchBtn fetchTest={this.props.fetchTest} />
                </div>
            )
        }
    }
    
    //Fetchbtn
    handleClick = (e) => {
        this.props.fetchTest();
    }

    感觉
    1.不用引中间件(redux-thunk、redux-promise)了,也不用考虑中间件执行顺序等问题。
    2.逻辑写在容器组件里面,感觉没什么毛病,UI组件如果需要,都可以拿到。

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    • 执白先行 普通会员 1楼
      502 Bad Gateway

      502 Bad Gateway


      nginx
    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部