javascript - 尝试让操作和 reducer 工作时出错

标签 javascript reactjs redux react-redux

我正在关注一篇博客文章,尝试在我的应用程序中实现用户登录

https://auth0.com/blog/secure-your-react-and-redux-app-with-jwt-authentication/

它建议在我的操作中执行以下操作

// actions.js

export const LOGIN_REQUEST = 'LOGIN_REQUEST'

function requestLogin(creds) {
  return {
    type: LOGIN_REQUEST,
    isFetching: true,
    isAuthenticated: false,
    creds
  }
}

// .....

export function loginUser(creds) {

  let config = {
    method: 'POST',
    headers: { 'Content-Type':'application/x-www-form-urlencoded' },
    body: `username=${creds.username}&password=${creds.password}`
  }
  console.log(creds) // <-- this works
  return dispatch => {
    console.log(creds) // <-- this doesnt work and everything after it doesnt work

    // We dispatch requestLogin to kickoff the call to the API
    dispatch(requestLogin(creds))

    return fetch('http://localhost:3001/sessions/create', config)
      .then(response =>
        response.json().then(user => ({ user, response }))
            ).then(({ user, response }) =>  {
        if (!response.ok) {
          // If there was a problem, we want to
          // dispatch the error condition
          dispatch(loginError(user.message))
          return Promise.reject(user)
        } else {
          // If login was successful, set the token in local storage
          localStorage.setItem('id_token', user.id_token)
          localStorage.setItem('id_token', user.access_token)
          // Dispatch the success action
          dispatch(receiveLogin(user))
        }
      }).catch(err => console.log("Error: ", err))
  }
}

但是,一旦函数到达 returndispatch => { 部分,就会引发错误 enter image description here

--- 编辑 --- 下面的答案修复了控制台错误,但引入了新错误

我的 redux chrome 插件不再看到我的 redux 商店 enter image description here

最佳答案

您似乎没有设置 Redux Thunk,这是一个允许您进行异步操作的 Redux 库。

在本教程中,您linked ,解释了如何设置:

import thunkMiddleware from 'redux-thunk'


let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore)

您应该阅读有关 Redux Thunk 的更多信息 here .

关于javascript - 尝试让操作和 reducer 工作时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44035108/

相关文章:

javascript - 根据输入改变CSS

javascript - AngularJS ng-model 不工作?

javascript - redux 在哪里做计算?

reactjs - 根据用户角色隐藏一些 React 子组件

javascript - redux react 错误 : Actions must be plain objects

javascript - JQuery - 重置计数时再次绑定(bind)()

javascript - Firebase JavaScript : Callback function does not return anything

javascript - 如何在未安装的组件上修复 'index.js:1446 Warning: Can' t 调用 setState(或 forceUpdate)...“在 ReactJS 中

javascript - 更改工具栏中的图标缩放react-apexchart

javascript - native react : render function not being called after state change