【问题标题】:Redux async actions and view updatesRedux 异步操作和查看更新
【发布时间】:2019-06-17 09:23:07
【问题描述】:

我正在尝试为网站实现登录表单,这是我在 React 上的第一个项目,所以我还是个初学者。

为此,我在我的 redux reducer 中使用了 socket.io-client。 问题是,它没有正确更新本地道具。

这是我的观点的代码:

const mapStateToProps = state => {
    return {
        profile: state.profileReducer.profile
    }
}

const mapDispatchToProps = dispatch => {
    return {
        dispatch: action => {
            dispatch(action)
        }
    }
}

...

handleConnection = () => {
    const { profile } = this.props

    this.props.dispatch({ type: 'CONNECT_USER' })

}

...

export default connect(mapStateToProps, mapDispatchToProps)(LoginPage)

这是减速器的作用:

import io from 'socket.io-client'

const host = [SERVER_URL]

const socketConnection = io.connect(host, {path: [PATH], secure: true})

const initialState = {
    profile: {
        token: null,
        username: '',
        password: ''
    }
}

function profileReducer(state = initialState, action) {
    switch(action.type) {

        ...

        case 'CONNECT_USER':
            let tempProfile = {...state.profile}

            socketConnection.emit('login', tempProfile.username + ';' + tempProfile.password)

            socketConnection.on('check', msg => {
                if (msg !== null && msg !== '')
                    tempProfile.token = msg

                return {
                    ...state,
                    profile: tempProfile
                }
            })

            return state

        ...
    }
}

“检查”套接字操作返回一条消息,其中包含我需要存储的用户连接令牌,以确保连接已完成并被允许。 问题是,它不会更新存储值。如果我直接更新reducer的状态而不是临时配置文件,它会部分工作:视图道具没有正确更新,但'handleConnection'函数内的'setInterval'中的'console.log(profile)'显示令牌值(但 Chrome React Inspector 中的 props 没有更新)。

我真的不明白发生了什么。我想 socket.io 'on' 功能在我的操作'return'之前没有完成,但我不知道如何处理它。

有人知道我该如何解决这个问题吗?

谢谢!

【问题讨论】:

  • 嗨@garcia.dev - 你应该保持你的减速器。意味着您不能在其中执行副作用。我的建议是将登录逻辑从减速器移到组件之外。然后通过您的操作的有效负载(例如this.props.dispatch({ type: 'CONNECT_USER', payload: {pass_fields_through_here}))将所有必需的数据传递给它

标签: reactjs redux socket.io react-redux


【解决方案1】:

减速器本质上总是同步的。如果你想在你的 reducer 中执行异步操作(比如你试图建立的套接字连接),那么你需要使用像 ThunkSaga 这样的中间件来实现一样。

在您的情况下,它总是从最后一个 return 语句返回现有状态。

【讨论】:

  • 感谢您的回答!我设法集成了 redux-thunk,它现在可以工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 2019-12-17
  • 2017-09-26
  • 2016-06-02
相关资源
最近更新 更多