Promise async/await 不起作用 - 数组未更新

发布于 2025-01-11 17:49:14 字数 2800 浏览 3 评论 0原文

单击复选框后,我会立即使用 action/reducerdispatch 更新数组 addItems,但是当我检查数组时,它不是最新的。为了解决这个问题,我引入了 async/await 承诺(我是承诺的新手),但是当我签入时,数组仍然没有更新!我缺少什么?

const [addItems, dispatch] = useReducer((state, action) => {
switch (action.type) {
  case "add":
    return [
      ...state,
      {
        id: state.length,
        data: action.data
      }
    ];
  default:
    return state;
}
}, []);

const callDispatch = (sampleId, testId, checked) => {
      console.log("sample: " + sampleId + " t: " + testId + " bool: " + checked);          

      const linkedData = {
        sampleId: sampleId,
        TestId: testId,
        isSelected: checked
      };
  
      return Promise.resolve(
      dispatch({
        type: "add",
        data: linkedData
      }));
    };

const linkDataHandler = async(samplesData, test, e) => {
    
    const isSelected =  e.target.checked;

    await callDispatch(samplesData.id, test.testList.id, isSelected) 
    .then( r =>{
        //addItems is still not updated when checked here
    }})
    .catch(error => console.log(error));

 <input
    type="checkbox"
    onClick={(e) => {
      linkDataHandler(sampleObj, testObj, e);
    }}
  />

工作示例: https://codesandbox.io/s /staging-moon-xv1ku5?file=/src/App.js

Sol1: 尝试使用回调如下但不起作用

import React, { useReducer, useEffect, useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import { useRef } from "react";

export default function App() {
const [addItems, dispatch] = useReducer((state, action) => {
switch (action.type) {
  case "add":
    return [
      ...state,
      {
        id: state.length,
        data: action.data
      }
    ];
  default:
    return state;
 }
 }, []);

  const linkDataHandler = (samplesData, test, e) => {
  const isSelected = e.target.checked;
  console.log(isSelected);
  callDispatch(samplesData, test, isSelected, (user) => {
  console.log(addItems);
  });
};
const callDispatch = (sampleId, testId, checked, callback) => {
const linkedData = {
  sampleId: sampleId,
  TestId: testId,
  isSelected: checked
};

callback(
  dispatch({
    type: "add",
    data: linkedData
  })
);
};

return (
<div className="App">
  <h1>Hello CodeSandbox</h1>
  <input
    type="checkbox"
    onClick={(e) => {
      linkDataHandler(1, 1, e);
    }}
  />
  ABC
</div>
);
}

Sol2:尝试添加useeffect

useEffect(() => {
console.log(addItems.length);
  }, addItems);

传递给 useEffect 的最后一个参数更改了渲染之间的大小。该数组的顺序和大小必须保持不变。

I am updating an array addItems as soon a checkbox is clicked, using action/reducer and dispatch but when I check the array it is not up to date. to resolve this I have introduced async/await promises (I am new to promises) but when I check in then the array is still not updated! What am I missing?

const [addItems, dispatch] = useReducer((state, action) => {
switch (action.type) {
  case "add":
    return [
      ...state,
      {
        id: state.length,
        data: action.data
      }
    ];
  default:
    return state;
}
}, []);

const callDispatch = (sampleId, testId, checked) => {
      console.log("sample: " + sampleId + " t: " + testId + " bool: " + checked);          

      const linkedData = {
        sampleId: sampleId,
        TestId: testId,
        isSelected: checked
      };
  
      return Promise.resolve(
      dispatch({
        type: "add",
        data: linkedData
      }));
    };

const linkDataHandler = async(samplesData, test, e) => {
    
    const isSelected =  e.target.checked;

    await callDispatch(samplesData.id, test.testList.id, isSelected) 
    .then( r =>{
        //addItems is still not updated when checked here
    }})
    .catch(error => console.log(error));

 <input
    type="checkbox"
    onClick={(e) => {
      linkDataHandler(sampleObj, testObj, e);
    }}
  />

A working sample: https://codesandbox.io/s/staging-moon-xv1ku5?file=/src/App.js

Sol1: Tried using Callback as follows but didnot work

import React, { useReducer, useEffect, useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import { useRef } from "react";

export default function App() {
const [addItems, dispatch] = useReducer((state, action) => {
switch (action.type) {
  case "add":
    return [
      ...state,
      {
        id: state.length,
        data: action.data
      }
    ];
  default:
    return state;
 }
 }, []);

  const linkDataHandler = (samplesData, test, e) => {
  const isSelected = e.target.checked;
  console.log(isSelected);
  callDispatch(samplesData, test, isSelected, (user) => {
  console.log(addItems);
  });
};
const callDispatch = (sampleId, testId, checked, callback) => {
const linkedData = {
  sampleId: sampleId,
  TestId: testId,
  isSelected: checked
};

callback(
  dispatch({
    type: "add",
    data: linkedData
  })
);
};

return (
<div className="App">
  <h1>Hello CodeSandbox</h1>
  <input
    type="checkbox"
    onClick={(e) => {
      linkDataHandler(1, 1, e);
    }}
  />
  ABC
</div>
);
}

Sol2: tried adding useeffect

useEffect(() => {
console.log(addItems.length);
  }, addItems);

The final argument passed to useEffect changed size between renders. The order and size of this array must remain constant.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文