我在React类中有一个函数“ sendMessage”:
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中检索“响应”,然后将这些数据放入变量“ chInfo”中,并将其分配为Redux状态,然后在确认后立即打印。
和Redux Action函数,“ setCurrentChannel”看起来像:
export const setCurrentChannel = channel => {
return {
type: SET_CURRENT_CHANNEL,
payload: {
currentChannel: channel
}
};
};
减速器“ SET_CURRENT_CHANNEL”如下所示:
export default function (state = initialState, action) {
switch (action.type) {
case SET_CURRENT_CHANNEL:
return {
...state,
currentChannel: action.payload.currentChannel
};
...
后端Socket.io部分看起来像(我使用MongoDB):
socket.on('createChannelPM', async (data, callback) => {
const channel = await PrivateChannel.create({
...data
});
callback(channel)
});
console.log说:
问题:最后一个输出“ this.props.currentChannel”应该与第一个输出“ chInfo”相同,但是要有所不同,只能打印出先前的值。
但是,在Redux chrome扩展程序中,“ this.props.currentChannel”与“ chInfo”完全相同:
将新的Redux状态设置为Redux State之后,如何立即获得和使用?
答案 0 :(得分:1)
您不会立即在 this.props.currentChannel 中获得更新的值。更新Redux存储后,将再次调用MessageForm组件的mapStateToProps。此处状态 state.channel.currentChannel 将映射到 currentChannel 。在此组件中,您将获取更新的道具,这些道具将通过 this.props.currentChannel 访问。
我相信您希望使用可以处理的最新数据来呈现UI。