我最近一直在用reactredux 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确实给了我最新的messagesarray.但是,如果我在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 <></>
}

所以我知道这里发生了什么,但如果我能得到任何解决方案或提示的回应,那就太好了.如果我哪里错了,请纠正我.

推荐答案

如果你想直接从mailTime函数访问存储,你可以在你的组件内部使用const store = useStore(),然后在mailTime函数调用store.getState()来访问状态,但我不认为这是一个最好的解决方案.如果你需要做一些链式API请求,我会建议你把那部分转移到中间件上.

Javascript相关问答推荐

在服务器上放置了Create Reaction App Build之后的空白页面

当试图显示小部件时,使用者会出现JavaScript错误.

为什么Mutations 观察器用微任务队列而不是macrotask队列处理?

可更改语言的搜索栏

使用POST请求时,Req.Body为空

JQuery Click事件不适用于动态创建的按钮

钛中的onClick事件需要在两次点击之间等待几秒钟

OpenAI转录API错误请求

WebSocketException:远程方在未完成关闭握手的情况下关闭了WebSocket连接.&#三十九岁;

如何组合Multer上传?

更改agGRID/Reaction中的单元格格式

Cherrio JS返回父div的所有图像SRC

如何在尚未创建的鼠标悬停事件上访问和着色div?

对不同目录中的Angular material 表列进行排序

如何在Highlihte.js代码区旁边添加行号?

AstroJS混合模式服务器终结点返回404

我在从侧面到内部的react 中面临着推翻观点的问题

Electron -如何指向ASAR生成的应用程序之外的路径

根据选定内容或设置编号将项目添加到数组

用对象填充数组的快速方法