【问题标题】:react hooks first dispatch causes other muplitple dispatch to fire twice反应钩子第一次调度导致其他多次调度触发两次
【发布时间】:2020-05-14 12:17:39
【问题描述】:

如果我向useEffect() 添加更多的调度,它会导致以下所有事件触发两次。下面的例子。

这是完整的代码。按您想要的任何其他顺序删除 cmets

ps。 idk如何让它作为代码运行sn-p

pps。我以this question 为例

import React, { useReducer, useEffect } from "react";
const url = `https://picsum.photos/v2/list?page=3&limit=1`;


function reducer(data, action) {
  console.log('reducer triggered', action.type);
  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;
    case "INI2":
      return action.payload;
     case "INI3":
      return action.payload;
    default:
      return
  }
}

function App() {
  const [data, dispatch] = useReducer(reducer, null);

  useEffect(() => {
    //dispatch({type: "INI2"}); // uncommment this to get 2 reducer messages from each below
    console.log("here");  
    fetch(url)
      .then(async response => {
        dispatch({type: "INITIALIZE",payload: (await response.json())});
        //dispatch({type: "INI3"});  // uncomment this to see that every new dispatch is doubled after first one
      })
      .catch(error => {console.log(error);});
  }, []);

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

export default App

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    这只是 React.StrictMode 出现在您的应用程序中的结果

    根据React Documentation

    严格模式不能自动为您检测副作用,但它 可以通过使它们更具确定性来帮助您发现它们。 这是通过故意双重调用函数来完成的

    传递给 useState、useMemo 或 useReducer 的函数是双重调用的一部分,这就是为什么您会在案例中看到这种行为

    Expected Working demo without React.StrictMode

    【讨论】:

    • 现在我明白了。谢谢。如何禁用它?
    • 您需要从组件层次结构中删除 。如果你使用 create-react-app ,它必须在 index.js 中
    猜你喜欢
    • 2020-01-12
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 2019-12-09
    • 2019-07-18
    相关资源
    最近更新 更多