我正在尝试通过Redux的fetch方法进行api调用,我创建了一些操作类型,例如fetch_start,fetch_success和fetch_failed。
但是我不能让我的减速器一无所有。当我检查redux dev工具时,也有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
})
})
}
}
答案 0 :(得分:1)
您必须为每个操作在化简器中返回新状态
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
}