React Hook useReducer始终运行两次

时间:2020-04-07 00:53:47

标签: reactjs react-hooks use-reducer

安装组件后,我正在从公共API加载数据。加载数据后,我会将其传递给reducer,但它始终会触发两次。这就是我所拥有的:

def calcStdDev(collection):
    # Get mean of the collection, initialise accumulator and count.

    mean = calcMean(collection)
    accum = 0, count = 0
    for item in collection:
        # Accumulate each '(item-mean) squared' value.

        diff = item - mean
        accum = accum + diff * diff

    # Avoid dive by zero, you choose what to do.

    if count < 2:
        handle too-small collection somehow

    # Divide and square root for result.

    return sqrt(sum / (count - 1))

您可以看到该组件正在等待数据填充化简器,当class Car(val horsepowers: Int) { companion object Factory { val cars = mutableListOf<Car>() fun makeCar(horsepowers: Int): Car { val car = Car(horsepowers) cars.add(car) return car } } 也被调用两次时,但是直到我需要调用val car = Car.makeCar(150) println(Car.Factory.cars.size) 时,我才开始关心它,因为在这种情况下,它将两个空白对象添加到数组中,而不是仅一个。我没有介绍副作用的文档,但是无法解决它。

处理此问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

这是我要处理的问题。 它重新运行动作效果的主要原因是因为组件功能中包含了reducer。我还继续解决了其他几个问题。

由于获取工作原理,获取代码略有不足。您必须从响应中获得数据类型,该响应给出另一个承诺而不是直接提供数据。

您还需要使用{}进行渲染,以表明您使用的是JavaScript而不是文本。

import React, { useReducer, useState, useEffect } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";
const url = `https://picsum.photos/v2/list?page=3&limit=1`;
function App(props) {
  const [data, dispatch] = React.useReducer(reducer, null);

  useEffect(() => {
    fetch(url)
      .then(async response => {
        dispatch({
          type: "INITIALIZE",
          payload: (await response.json())
        });
      })
      .catch(error => {
        console.log(error);
      });
  }, []);

  const addNew = () => {
    dispatch({ type: "ADD_NEW" });
  };
  console.log("here");
  return (
    <>
      <div>{data ? JSON.stringify(data) : "No Data Yet"}</div>
      <button onClick={addNew}>Test</button>
    </>
  );
}

render(<App />, document.getElementById("root"));
function reducer(data, action) {
  switch (action.type) {
    case "INITIALIZE":
      console.log(action.payload, "Initialize");
      return action.payload;
    case "ADD_NEW":
      const newData = { ...data };
      newData.info = newData.info || [];
      newData.info.push({});
      console.log(newData);
      return newData;
  }
}
相关问题