使用带有promise的

时间:2017-04-06 15:56:00

标签: javascript reactjs ecmascript-6 redux

export function postRegister(credentials) {
    console.log(credentials);

    return dispatch => {
        return fetch('/user/register', {
            method: 'post',

            body: JSON.stringify(credentials),

            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
    }
}

我对上面的代码几乎没有疑问。

  1. 我可以使用export()=> {}而不是在这里写单词功能?为了保持清洁。

  2. dispatch是一个全局变量?我没有在文件中的任何地方看到它被导入或需要。

  3. 此处是否需要指定标题?我在每次api电话中都看到了这一点。

  4. 为什么在这个承诺电话中没有抓到?总的来说代码不好?

2 个答案:

答案 0 :(得分:1)

  1. No really, you could but you need a name to actually use it in your components.
  2. No, dispatch is a parameter of the arrow function, you can also define getState to access the current redux state. By the way, you can totally assign new names if you want.
  3. It depends on your server, but generally if you are using a JSON API, you would want to send that header.
  4. Yes, overall that code doesn't look good, I would recommend using a middleware to handle the fetch requests, your actions should only send the configurations such as the url, body, method, etc... and your middleware should handle adding common headers (such as the content-type).

You could have an action like this:

export function postRegister(credentials) {
  return {
    types: [REGISTER, REGISTER_SUCCESS, REGISTER_FAIL],
    promise: {
      url: '/user/register',
      data: credentials,
    },
  };
}

Something as simple as that, then your middleware should do the fetch and dispatch the action types based on the server response.

If you want to know more about how the middleware should handle the fetch request and dispatch the actions, make sure to take a look at my post here: https://stackoverflow.com/a/39971763/146718

答案 1 :(得分:0)

  1. 除非是导出默认值。因为以后你需要按名称导入它。

  2. 不,dispatch是传递给你的函数的参数:

    (dispatch)=> {}

  3. 完全取决于您的应用程序,服务器,请求等。

  4. 你可以添加自己的.catch((e)=> {}),或者使用一些拦截器来处理一般错误,从那里做一个dipatch并添加一个可以处理这些动作的reducer。你可以在这里阅读更多内容:

  5. What is the best way to deal with a fetch error in react redux?

相关问题