javascript - setState() 不改变值

标签 javascript reactjs

从昨天开始,我一直在为这个问题苦苦挣扎,但无法解决。

基本上,我们正在为餐厅制作一个网站,客户可以使用该网站点餐并付款。 我现在正在实现的功能是,当用户按下结帐按钮时,它会转到 /order_confirm 并显示所有已订购的菜单。我试图通过将 url 设置为 /order_confirm/id 来传递订单号,其中 id 是订单号。一切正常,除了当我执行 setState() 更改状态的 ordId 的值并将状态值传递给相应的类时,似乎 setstate 根本没有改变值。

handleCheckoutRequest = async () => {
const { tableNumber } = this.state;
const orderOrdered = 1;
const menuItemIds = this.props.menuItems.map((a) => a.id);
const menuItemCounts = this.props.menuItems.map((a) => a.count);

await API.post(`/orders/`, null, {
      params: { tableNumber, orderStatus: orderOrdered },
    })
      .then(async (response) => {
        const orderId = response.data.id; // this works

    await API.post(`/ordered_items/${orderId}`, null, {
      params: { menuItemIds, menuItemCounts },
    })
      .then((response) => {
        this.setState({
            responses: ["Successfully added order items"], // this works
            responseStatus: "success", // this works as well
            ordId: orderId, // this doesn't
        });
        console.log(orderId); // display 25 on the console (which is right)
        console.log(this.state.ordId); // display -1 which is the default value
      })
      .catch((error) => {
        console.log(error);
      });
  })
};

我在控制台中收到此错误。

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

我试过设置速度,使用 setState() 中的箭头函数,在外部声明方法并使用该方法更改值。这一切都没有用。


这是 handleCheckout 方法。
handleCheckout = () => {
  const { menuItems } = this.props;
  const { tableNumber } = this.state;
  let responses = [];
  if (tableNumber === -1 || !tableNumber)
    responses.push("No table has been selected");
  if (menuItems.length < 1)
    responses.push("No menu items have been added to cart");
  if (responses.length > 0) {
    this.setState({ responses, responseStatus: "fail" });
    return;
  }
  this.setState({ responses: [], responseStatus: "" });

  this.handleCheckoutRequest();
};

这是我将状态作为 Prop 传递的部分。

<div className="cart__bottom">
   <Checkout
      id={this.state.ordId}
      onTableChange={this.handleTableChange}
      onCheckout={this.handleCheckout}
      responses={responses}
      responseStatus={responseStatus}
   />
</div>

这是它传递的地方的 render()

render() {
const { id, onTableChange, onCheckout, responses, responseStatus } = this.props;
return (
  <div className="cart__checkout">
    <Response responses={responses} responseStatus={responseStatus} />
    <input
      className="input mb-2"
      type="number"
      name="tableNumber"
      placeholder="Table Number"
      onChange={onTableChange}
    />
    <Link to={{
      pathname: "/order_confirm/" + id
    }}>
      <button
        className="button is-primary is-fullwidth"
        onClick={onCheckout}
      >
        Checkout
      </button>
    </Link>
  </div>
);

我还发现了一篇文章,它似乎可以解决我的问题。唯一的障碍是我对 React 不够好,无法应用这些解决方案。
Avoid React state update warnings on unmounted components

最佳答案

尽量不要将 async await 与正常的 promise 混在一起。坚持其中之一。 也尽量不要嵌套 promise,因为那会给你带来回调 hell 。

const postOrder = async () => {
  const apiPostOrdersResponse = await API.post(`/orders/`, null, {
    params: { tableNumber, orderStatus: orderOrdered },
  });

  const orderId = apiPostResponse.data.id;

  const apiPostOrderItemResponse = await API.post(
    `/ordered_items/${orderId}`,
    null,
    {
      params: { menuItemIds, menuItemCounts },
    }
  );

  this.setState({
    responses: ['Successfully added order items'],
    responseStatus: 'success',
    ordId: orderId,
  });
};

关于javascript - setState() 不改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66322406/

相关文章:

reactjs - React 路由器位置仅在某些组件中更新

node.js - 即使存在匹配值,Jest/Jasmine .toContain() 也会失败

Javascript变量范围问题

javascript - JSLint 不期望我的波浪号

JavaScript Node.js 日期比较和数组按日期排序

javascript - 设置状态和过滤。跳过数据 - React/Javascript

reactjs - DataGrid 上的 CloneButton 转到编辑页面

javascript - 如何让 Angular 应用程序访问后端 API

javascript - 检测到 console.warn 消息

javascript - React-Native 将两个数组合并为一个