Redux 如何使用 fetch 方法分派多个动作类型

Redux how dispatch multiple action types with fetch method

我正在尝试使用 Redux 的 fetch 方法进行 api 调用,我创建了一些操作类型,例如 fetch_start、fetch_success 和 fetch_failed。

但我的减速器对我来说什么都不能 return。当我检查 redux 开发工具时,有 3 种动作类型也有效。我错在哪里?

我正在使用 thunk、redux

这是我的组件:

class SignInComponent extends Component {

    signIn = () => {
        this.props.signIn()
    }

    render() {

    return (
      <Row className="justify-content-md-center">
         <Col lg={4}>
              <button type="button" onClick={this.signIn}>
              </button>
              </Col>
      </Row>
    )
  }
}


  const mapStateToProps = state => ({
    users: state.users
  })

  function mapDispatchToProps(dispatch) {
    return {
      signIn: bindActionCreators(signIn, dispatch)
    }
  } 

  export default connect(mapStateToProps, mapDispatchToProps)(SignInComponent)

这是我的减速器:

import { SIGNIN_START, SIGNIN_SUCCESS, SIGNIN_FAILED } from '../../actions/Auth/SignIn'

let initialState = []

export default (state = initialState, action) => {
    switch (action.type) {
        case SIGNIN_START:
            return console.log('start')
        case SIGNIN_SUCCESS:
            return console.log("success")  
        case SIGNIN_FAILED:
            return console.log("fail")        
        default:
            return state
    }
}

这是我的操作:

export const SIGNIN_START = 'SIGNIN_START';
export const SIGNIN_SUCCESS = 'SIGNIN_SUCCESS';
export const SIGNIN_FAILED = 'SIGNIN_FAILED';

export const signIn = () => {
    return(dispatch) => {
        dispatch({
            type: SIGNIN_START
        })
        fetch('https://api.com/signIn')
        .then((response) => {
            dispatch({
                type: SIGNIN_SUCCESS
            })
        })
        .catch((err) => {
        dispatch({
            type: SIGNIN_FAILED
        })
        })
    }
}

你必须return减速器中每个动作的新状态

return console.log();

只会 returns undefined.

改为

switch (action.type) {
  case SIGNIN_START:
     console.log('start')
     return [...state];
  case SIGNIN_SUCCESS:
     console.log("success")
     return [...state];
  case SIGNIN_FAILED:
     console.log("fail");
     return [...state];    
  default:
     return state
 }