异步操作:获取返回的类而不是调度函数



我正在使用 react、redux-thunk、登录的异步操作 获取一个调度函数,就像它应该是 注销的异步操作 在安慰调度时获取一个具有目标等事件属性的类。

导航栏.jsx

const Navbar = ({ profile, history }) => {
    return (
        <nav>
            <Button type="danger" onClick={signOut(history)}>
               Logout
            </Button>
        </nav>
    )
}
const mapStateToProps = state => ({
    profile: state.firebase.profile,
})
const mapDispatchToProps = dispatch => ({
    signOut: history => dispatch(signOut(history)),
})
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(withRouter(Navbar))

异步操作

export const signIn = ({ email, password }, history) => {
    return (dispatch, getState) => {
        auth.signInWithEmailAndPassword(email, password)
            .then(() => {
                console.log('TCL: dispatch', dispatch) // returns dispatch function
                history.push('/')
                dispatch({ type: 'LOGIN_SUCCESS' })
            })
            .catch(err => {
                dispatch({ type: 'LOGIN_ERROR', err })
            })
    }
}
export const signOut = history => (dispatch, getState) => {
    auth.signOut()
        .then(() => {
            console.log('TCL: dispatch', dispatch) // return class and throws dispatch is not a function
            history.push('/login')
            dispatch({ type: 'SIGNOUT_SUCCESS' })
        })
        .catch(err => console.log(err))
}

找到了解决方案 - 我还需要从道具中获取signOut

import {signOut} from '../store/actions/authActions'
const Navbar = ({ profile, history, signOut }) => { // adding "signOut" solved it.
    return (
        <nav>
            <Button type="danger" onClick={() => signOut(history)}>
               Logout
            </Button>
        </nav>
    )
}

在挂接事件处理程序时调用 signOut 函数,该事件处理程序将结果分配给onClick处理程序,即

onClick={signOut(history)}

这意味着onClick会触发(dispatch, getState) => ...并解释为什么dispatch=== evt 。您需要使用事件处理程序包装调用以吞下 click 事件:

onClick={() => signOut(history)}

最新更新