【问题标题】:Redux how dispatch multiple action types with fetch methodRedux 如何使用 fetch 方法调度多种动作类型
【发布时间】:2019-07-07 07:14:37
【问题描述】:

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

但我的减速机无法返回给我。当我检查 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
        })
        })
    }
}

【问题讨论】:

  • 你正在调度对象而不是函数,你必须调度函数
  • 你的代码是正确的,但是你并没有从你的reducer返回你的状态,你只是返回一个console.log。它至少需要返回初始状态。

标签: reactjs redux redux-thunk


【解决方案1】:

你必须在 reducer 中为每个动作返回新状态

return console.log();

将简单地返回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
 }

【讨论】:

  • 我明白一切都很好,非常感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-23
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多