什么回来了?

时间:2017-03-03 06:26:52

标签: reactjs redux react-redux redux-thunk

我正在阅读下面的示例中使用React,Redux和Thunk编写的JavaScript:

在actions.js中创建动作:

function fetchPosts(subreddit){
    return dispatch => {
            dispatch(requestPosts(subreddit))
            return fetch(`...URL...`)
                    .then(response => response.json())
                    .then(json => dispatch(receivePosts(subreddit, json)))
    }
}

export function fetchPostsIfNeeded(subreddit) {
  return (dispatch, getState) => {
    if (shouldFetchPosts(getState(), subreddit)) {
      return dispatch(fetchPosts(subreddit))
    }
  }

" fetchPosts(subreddit)"返回?

我无法理解"返回dispatch =>"是即可。

此函数已导入并在容器中用于调度操作,因此我 思考"派遣"是从容器中的&react-redux'导入的函数,如下所示:

import {fetchPostsIfNeeded} from "../actions"
import {connect} from "react-redux"
...
componentDidMount() {
    const { dispatch, selectedSubreddit } = this.props
    dispatch(fetchPostsIfNeeded(selectedSubreddit))
  }
...

"发送"在箭头之前表示一个函数," dispatch(requestPosts(subreddit))"?

发出一个参数"(dispatch)"是否缩写为ES2015?

1 个答案:

答案 0 :(得分:2)

来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

// Parentheses are optional when there's only one parameter:
(singleParam) => { statements }
singleParam => { statements }

因此,dispatch => {...}正在使用一个参数dispatch制作箭头函数。 fetchPosts(subreddit)返回单箭头功能。

关于{ disppatch, selectedSubreddit } = this.props的废话是一种称为解构分配的东西。手册:MDN Destructuring Assignment

它的本质是:

var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true

所以是的,dispatch正在被this.props拉出来,这显然是一个反应组件! ReactJS Components and Props