Javascript Can';t在从Socket.IO获取响应后立即使用新的redux状态
我在React类中有一个函数“sendMessage”:Javascript Can';t在从Socket.IO获取响应后立即使用新的redux状态,javascript,reactjs,redux,socket.io,react-redux,Javascript,Reactjs,Redux,Socket.io,React Redux,我在React类中有一个函数“sendMessage”: class MessageForm extends React.Component { ... sendMessage = async () => { const { message } = this.state; if (message) { this.setState({ loading: true }); if (this.props.isPrivateChannel ===
class MessageForm extends React.Component {
...
sendMessage = async () => {
const { message } = this.state;
if (message) {
this.setState({ loading: true });
if (this.props.isPrivateChannel === false) {
socket.emit("createMessage", this.createMessage(), (response) => {
this.setState({ loading: false, message: "", errors: [] });
});
} else {
if (this.state.channel && this.state.channel._id === undefined) {
socket.emit("createChannelPM", this.state.channel, async (response) => {
const chInfo = { ...response, name: this.props.currentChannel.name };
console.log("chInfo : ", chInfo);
await this.props.setCurrentChannel(chInfo).then((data) => {
if (data) {
console.log("data : ", data);
console.log("this.props.currentChannel : ", this.props.currentChannel);
}
});
});
}
...
function mapStateToProps(state) {
return {
isPrivateChannel: state.channel.isPrivateChannel,
currentChannel: state.channel.currentChannel,
};
}
const mapDispatchToProps = (dispatch) => {
return {
setCurrentChannel: async (channel) => await dispatch(setCurrentChannel(channel)),
}
};
在这里,在sendMessage函数中,我从socket.io中检索“response”,然后将此数据放入变量“chInfo”中,并将其分配给Redux状态,然后在分配后立即打印它
和Redux操作函数,“setCurrentChannel”看起来像:
export const setCurrentChannel = channel => {
return {
type: SET_CURRENT_CHANNEL,
payload: {
currentChannel: channel
}
};
};
export default function (state = initialState, action) {
switch (action.type) {
case SET_CURRENT_CHANNEL:
return {
...state,
currentChannel: action.payload.currentChannel
};
...
减速器“设置当前通道”如下所示:
export const setCurrentChannel = channel => {
return {
type: SET_CURRENT_CHANNEL,
payload: {
currentChannel: channel
}
};
};
export default function (state = initialState, action) {
switch (action.type) {
case SET_CURRENT_CHANNEL:
return {
...state,
currentChannel: action.payload.currentChannel
};
...
后端Socket.io部分看起来像(我使用MongoDB):
console.log显示:
问题:最后一个输出“this.props.currentChannel”应该与第一个输出“chInfo”相同,但不同,只打印出以前的值。
但是,在Redux chrome扩展中,“this.props.currentChannel”与“chInfo”完全相同:
如何在将新更改的Redux状态分配到Redux状态后立即获取并使用它?您不会在this.props.currentChannel中立即获得更新的值。更新redux存储后,将再次调用MessageForm组件的MapStateTrops。此处状态state.channel.currentChannel将映射到currentChannel。在此组件中,您将获得更新的道具,这些道具将作为this.props.currentChannel访问 我相信你想用你能做的最新数据呈现UI