如何设置redux传奇

时间:2017-08-12 19:19:06

标签: reactjs redux redux-saga

我正在尝试设置redux-saga,但我不确定是否会导致问题。

  

未捕获错误:操作必须是普通对象。使用自定义中间件进行异步操作。

这是一个常见错误,但我无法弄清楚这一点。我使用了redux和redux-saga中的示例来设置代码。

class Login extends Component {
  static propTypes = {
    isAuthenticated: PropTypes.bool,
    loginRequest: PropTypes.func
  }

  _onSubmit = () => {
    const {userName, password} = this.state

    const credentials = { userName, password }
    this.props.loginRequest(credentials)
  }
}

const mapStateToProps = state => ({
  isAuthenticating: state.login.isAuthenticating
})

const mapDispatchToProps = dispatch => bindActionCreators({
  loginRequest
}, dispatch)

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Login)

./动作

export const loginRequest = credentials => {
  return dispatch => {
    dispatch({
      type: types.LOGIN_REQUEST,
      credentials
    })
  }
}

./存储

export const history = createHistory()
const sagaMiddleware = createSagaMiddleware()

const initialState = {}
const enhancers = []
const middleware = [
  sagaMiddleware,
  routerMiddleware(history)
]

const composedEnhancers = compose(
  applyMiddleware(...middleware),
  ...enhancers
)

const store = createStore(
  rootReducer,
  initialState,
  composedEnhancers
)

sagaMiddleware.run(loginSaga)

export default store

./佐贺

    function postLogin (credentials) {
  credentials.grant_type = 'password'
  const payload = {
    method: 'post',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    data: encoder(credentials),
    url: `${config.IDENTITY_URL}/Token`
  }

  return axios(payload)
}

function * loginRequest (action) {
  try {
    const data = yield call(postLogin, action.credentials)
    yield put({ type: types.LOGIN_SUCCESS, data })
  } catch (err) {
    yield put({ type: types.LOGIN_FAILURE, err })
  }
}

function * loginSaga () {
  yield takeLatest('LOGIN_REQUEST', loginRequest)
}

export default loginSaga

1 个答案:

答案 0 :(得分:1)

问题在错误消息中准确描述,您的操作必须是普通对象。这意味着您的动作创建者必须返回普通对象,例如:

export const loginRequest = credentials => {
  return {
    type: types.LOGIN_REQUEST,
    credentials
  }
}