const MyComponent = () => {
  const [avaliador, setAvaliador] = useState("");
  const [avaliadoresList, setAvaliadoresList] = useState([]);
  const [DataResultsTotal, setDataResultsTotal] = useState([]);

  const filters = useSelector((state) => state.filter);

  // not all consts is here, only to show the problem

  const fetchData = async (token) => {
    try {
      const responseResult = await axios.get(
        "http://apicall/example/all",
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      setDataResultsTotal(responseResult.data);
      setAreaProgs(responseResult.data.length);

      // and continuous some calc to send to updates the state and show to the user
      });
      setError(responseResult.data.erro);
    } catch (error) {
      console.error("something wrong", erro);
    }
  };

  useEffect(() => {
    setToken(localStorage.getItem("token"));
    fetchData(token);
  }, [token]);

  const handleChangeSelect = (event) => {
    setAvaliador(event.target.value);
    dispatch(updateFilters({ ["name"]: event.target.value }));
  };

  const shouldDisplay = (lev) => {
    let matchesSearchText = lev.noEncarregado
      .toUpperCase()
      .includes(filters.noEncarregado);

    // let matchesCategory = lev.id.toLowerCase().includes(filters.ids);
    //  filters.ids.length > 0
    //   ? filters.ids.some((id) => id == lev.category)
    //    : true;
    return matchesSearchText;
  };

  const filteredData = DataResultsTotal.filter((lev) => shouldDisplay(lev));
  setDataResultsTotal(filteredData); // the error goes here

  return (
    <Box
      paddingLeft={isOpen ? "80px" : "200px"}
      bgcolor={`${colors.slate[100]}`}
    >
      <Grid container>
        <Grid item xs={12} sm={6} md={6} lg={6}>
          <Box>
            <Typography
              variant="h4"
              sx={{
                fontWeight: "bold",
                marginLeft: "20px",
                marginTop: "20px",
              }}
            >
              text title
            </Typography>
            <Typography
              variant="h6"
              sx={{
                marginLeft: "20px",
                marginTop: "5px",
                marginBottom: "20px",
              }}
            >
              anotr text
            </Typography>
          </Box>
        </Grid>
        <Grid
          item
          xs={12}
          sm={6}
          md={6}
          lg={6}
          marginTop={"20px"}
          marginBottom={"10px"}
        >
          <Box
            display={"flex"}
            alignItems={"center"}
            height={"100%"}
            justifyContent={"flex-end"}
          >
            <DownloadBtn DownText={true} />
          </Box>
        </Grid>
        <Grid item xs={12} sm={6} md={3} lg={3}>
          <Box sx={{ mx: "10px", my: "5px" }}>
            <Box sx={{ minWidth: 150 }}>
              <FormControl fullWidth>
                <InputLabel id="demo-simple-select-label">
                  texttt
                </InputLabel>
                <Select
                  labelId="demo-simple-select-label"
                  id="demo-simple-select"
                  value={avaliador}
                  label="Avaliador"
                  onChange={handleChangeSelect}
                >
                  {avaliadoresList.map((avaliador) => (
                    <MenuItem key={avaliador} value={avaliador}>
                      {avaliador}
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </Box>
          </Box>
        </Grid>

        <Grid item xs={6} sm={6} md={3} lg={3}>
          <Box sx={{ mx: "10px", my: "5px" }}>
            <CardHome
              size="h7"
              sizedesc="h3"
              name="text"
              icon={
                <ListAltOutlinedIcon
                  sx={{
                    fontSize: "28px",
                    color: `${colors.greenAccent[800]}`,
                  }}
                />
              }
              description={<Counter from={0} to={showfiltereddata} />}
            />
          </Box>
        </Grid>
      </Grid>
    </Box>
  );
}

好的,我正试着用material 过滤一些东西-UI和Redux,过滤器一切正常,但我不知道我是如何重新计算过滤后的数据并显示给用户的.

在这段代码中,我将从Redux获得状态,带到页面,与从API调用获得的计算数据进行比较,并将其保存在常量上,但我需要再次重新计算这些过滤后的数据,但当我try 这样做时,会抛出"太多重新呈现",我知道为什么会发生这种情况,但我不知道处理它的更好方法,也许是2useEffects

推荐答案

你有一个无意的副作用.

const filteredData = DataResultsTotal.filter((lev) => shouldDisplay(lev));
setDataResultsTotal(filteredData); // <-- unconditional state update!

filteredData是一个新的数组引用,每次组件呈现时,以及每次状态更新排队并触发组件重新呈现时.

只需计算并直接使用派生的filteredData值,104使用它来更新真理的来源,例如filtersDataResultsTotal状态.从代码中删除无意的副作用setDataResultsTotal(filteredData);.

示例:

const shouldDisplay = (lev) => lev.noEncarregado
  .toUpperCase()
  .includes(filters.noEncarregado);

const filteredData = DataResultsTotal.filter(shouldDisplay);

const filteredData = React.useMemo(() => {
  const shouldDisplay = (lev) => lev.noEncarregado
    .toUpperCase()
    .includes(filters.noEncarregado);

  return DataResultsTotal.filter(shouldDisplay);
}, [DataResultsTotal, filters]);

从计算出的filteredData值而不是现在的DataResultsTotal状态渲染UI.

Javascript相关问答推荐

主要内部的ExtJS多个子应用程序

为什么getRecord()会因为与_logger相关的错误而失败?(使用Hedera SDK)

TypScript界面中的Infer React子props

防止用户在selectizeInput中取消 Select 选项

我不知道为什么setwritten包装promise 不能像我预期的那样工作

角色 map 集/spritebook动画,用户输入不停止在键上相位器3

使用javascript将Plotly Expandable Sparkline转换为HighCharter Plot在bslib卡中

你怎么看啦啦队的回应?

使用JQuery单击元素从新弹出窗口获取值

如何在文本字段中输入变量?

在我的index.html页面上找不到我的Java脚本条形图

环境值在.js文件/Next.js中不起作用

Puppeteer上每页的useProxy返回的不是函数/构造函数

有没有一种直接的方法可以深度嵌套在一个JavaScript对象中?

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

如何根据输入数量正确显示alert ?

是否设置以JavaScript为背景的画布元素?

固定动态、self 调整的优先级队列

rxjs在每次迭代后更新数组的可观察值

如何用react组件替换dom元素?