我最近一直在用react
和redux toolkit
.我刚刚遇到了一个奇怪的问题.
我有一个Reaction组件ChatUI
,其中有一个正常的javascript
函数nextQue
nextQue Function
It has a post
API call and the response is then dispatched to reducers to update the messages
state.
我希望mailTime
内的最新消息数组函数,因为我必须张贴他们.知道useSelector
是同步的,IS确实给了我最新的messages
array.但是,如果我在mailTime
函数内部和外部获得了所需的数据,但在函数内部获得了108,那么我就无法获得最新的messages
内部mailTime
函数
下面是查看的代码(您不必根据以下代码回答,您可以在全局讨论这些问题的解决方案.)
const ChatUI = () => {
const dispatch = useDispatch();
const messages = useSelector((state) => state.msg.messages);
const [loading, setLoading] = useState(true);
const mailTime = () => {
// const requestOptions = {
// method: "POST",
// headers: { "Content-Type": "application/json" },
// body: JSON.stringify({
// data: messages,
// }),
// };
// fetch(
// "https://api-url",
// requestOptions
// )
// .then((res) => res.json())
// .then((data) => {
// console.log("datdat", data);
// });
console.log("not latest", messages); //not getting the desired length
};
console.log("latest messages", messages); //getting the desired length
const nextQue = (message) => {
setLoading(true);
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: {details to be posted}
};
fetch(
"https://api-url",
requestOptions
)
.then((res) => res.json())
.then((data) => {
console.log("data...", data?.data[0]?.question);
dispatch(
msgActions.add({
meta_value: data?.data[0]?.question,
post_id: data?.data[0]?.id,
type: "bot",
})
);
if (!data?.data[0]?.id) {
setTimeout(() => {
setLoading(false);
console.log("messa", messages);
mailTime();
}, 1000);
}
});
};
return <></>
}
所以我知道这里发生了什么,但如果我能得到任何解决方案或提示的回应,那就太好了.如果我哪里错了,请纠正我.