【发布时间】:2020-07-28 18:37:16
【问题描述】:
我正在使用 Axios api,但遇到了问题。我只有在后端而不是前端有 Firestore 调用。我正在使用 React 和 Firestore 制作聊天应用程序,但我似乎无法弄清楚如何通过 Axios 调用而不是 Firestore 来获取连续数据。
它只更新一次,不会连续流式传输。我必须在前端调用 Firestore 吗?
这是我从 redux 操作中调用 axios 函数的代码。
componentDidMount() {
this.props.getChatList();
this.setState({
chats: Object.values(this.props.allMessages),
});
}
componentDidUpdate(prevProps) {
if (!equal(this.props.allMessages, prevProps.allMessages)) {
this.props.getChatList();
this.setState({
chats: Object.values(this.props.allMessages),
});
}
}
这就是使用 Axios 调用的数据动作函数。
export const getChatList = () => (dispatch) => {
dispatch({ type: "LOADING_DATA" });
API.get("messages")
.then((res) => {
dispatch({
type: "GET_MESSAGES",
payload: res.data,
});
})
.catch(() =>
dispatch({
type: "GET_MESSAGES",
payload: null,
})
);
};
【问题讨论】:
-
这是因为
componentdidmount中的this.props.getChatList();只被调用一次,并且它会第一次更新聊天。您将需要一种机制来持续调用您的后端以获取聊天记录。尝试使用 setInterval 连续调用后端。componentdidmount中的setInterval(() => this.props.getChatList(), 2000)之类的东西,以便每两秒调用一次getChatList()
标签: node.js reactjs redux google-cloud-firestore axios