在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)))//拿到请求结果

}

}

主要思路是:

这是一个特殊的action creator(返回了一个function)

在这个action creator里面,可以dispatch其他action

通过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 (

)

}

}

//Fetchbtn

handleClick = (e) => {

this.props.fetchTest();

}

感觉

1.不用引中间件(redux-thunk、redux-promise)了,也不用考虑中间件执行顺序等问题。

2.逻辑写在容器组件里面,感觉没什么毛病,UI组件如果需要,都可以拿到。