reactjs - React Hook useReducer 总是运行两次

标签 reactjs react-hooks use-reducer

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

function MyComponent(props) {
   function reducer(data, action) {
      switch (action.type) {
         case 'INITIALIZE':
            return action.payload;
         case 'ADD_NEW':
            const newData = {...data};
            newData.info.push({});
            return newData;
      }
   }

   const [data, dispatch] = React.useReducer(reducer, null);

   useEffect(() => {
      fetch(URL)
        .then(response => {
            dispatch({
               type: 'INITIALIZE',
               payload: response
            });
         })
        .catch(error => {
            console.log(error);
         });
   }, []);

   const addNew = () => {
      dispatch({ type: 'ADD_NEW' });
   }

   return(
       <>data ? data.info.length : 'No Data Yet'</>
   );

}

正如你所看到的,组件等待数据填充reducer,当INITIALIZE也被调用两次时,但我并不关心它,直到我需要调用 ADD_NEW,因为在这种情况下,它会向数组中添加两个空白对象,而不是只添加一个。我没有查看副作用的文档,但我无法解决它。

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

最佳答案

这是我处理这个问题的方法。 重新运行 Action 效果的主要原因是因为组件的函数中有 reducer 。我还继续解决了其他几个问题。

由于获取的工作方式,获取代码有点偏差。您必须从响应中获取数据类型,这会给出另一个 promise ,而不是直接提供数据。

您还需要使渲染使用 {} 来指示您使用的是 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;
  }
}

关于reactjs - React Hook useReducer 总是运行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61071171/

相关文章:

reactjs - 类型 'number' 不可分配给类型 'SetStateAction<undefined>' 。 - react

javascript - React Hook 在函数 "onSubmit"中调用,它既不是 React 函数组件也不是自定义 React Hook 函数

javascript - 为什么 useReducer hook 中使用 switch 语句来管理状态?

javascript - React-TypeScript : Expected 0 arguments, 但在 useReducer 上得到 1

javascript - react : VariableDeclarator ASTNodes are not handled by markPropTypesAsUsed

javascript - 将 axios 响应保存到状态 react Hook

reactjs - React.js 应用程序显示 404 未在 nginx 服务器中找到

reactjs - react Hook 。无法对已卸载的组件执行 React 状态更新

javascript - 为什么 useState React hook 会导致 Too much re-renders。 React限制渲染次数以防止无限循环

node.js - AWS 上的实时数据库