【发布时间】: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