在React应用程序内部部分更改状态(对象数组)

问题描述 投票:-2回答:1

我有一个事件处理程序,每次单击它时,我的应用程序都会崩溃。问题与其他声明之后的部分有关。我想要实现的是:我有一个带有3个按钮的页面,一旦单击1个按钮,它将在状态数组内添加一个对象,并将用户发送到下一页,该页面上他具有其他具有相同功能的按钮。我想,如果用户在浏览器中单击“上一步”并再次单击按钮,则要覆盖该对象相对于该页面的价格。对不起,我不知道该如何表达自己。

`import React, { useContext } from "react";
import { PagesContext } from "../model/PagesContext";
import {
  MainWrapper,
  MainText,
  ButtonsWrapper,
  Icon,
  SelectionsContainer,
  ButtonLabel
} from "../StyledComponents";

const Choices = ({ pagename, values }) => {
  const [price, setPrice, history] = useContext(PagesContext);
  const checker = price.some(item => item.url === history.location.pathname);
  const AddPrice = e => {
    values.forEach(element => {
      if (element.id === e.target.id && !checker) {
        setPrice([
          ...price,
          { price: element.price, url: history.location.pathname }
        ]);
        history.push(element.next);
      } else {
        setPrice(
          price.forEach(obj => {
            if (checker && element.id === e.target.id) {
              obj.price = element.price;
            }
          })
        );
        history.push(element.next);
      }
    });
  };
  return (
    <MainWrapper>
      <MainText>{pagename}</MainText>
      <ButtonsWrapper>
        {values.map(button => (
          <SelectionsContainer key={button.id}>
            <Icon
              onClick={AddPrice}
              src={"/svg-icons/" + button.icon}
              id={button.id}
              style={{ width: "100px", height: "100px" }}
            />
            <ButtonLabel>{button.name}</ButtonLabel>
          </SelectionsContainer>
        ))}
      </ButtonsWrapper>
    </MainWrapper>
  );
};
export default Choices;
`
reactjs react-router react-hooks
1个回答
1
投票

您正在使用依赖于旧值的新状态值来更新状态,您应该明确地使用此值:

setState((prevState) => {
  // Do whatever you need to the last state
  // Just make sure to return a new reference (replace). 
  // Don't send back the same object reference 
  // One example, could be:
  return({
    ...prevState,
    [prop]: updateSomething
  });
});

不要这样做:

setPrice(
 price.forEach(obj => {
  if (checker && element.id === e.target.id) {
    obj.price = element.price;
  }
  })
);
© www.soinside.com 2019 - 2024. All rights reserved.