>我添加多个调度来useEffect()
它会导致以下所有触发两次。下面是示例。
这是完整的代码。按所需的任何其他顺序删除评论
IDK 如何让它作为代码片段运行
.pps。我以这个问题为例
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
这只是 React.StrictMode 存在于您的应用程序中的结果
根据 React 文档
严格模式无法自动为您检测副作用,但它 可以通过使它们更具确定性来帮助您发现它们。 这是通过有意双重调用函数来完成的
传递给useState,useMemo或useReducer的函数是双重调用的一部分,这就是为什么您在您的案例中看到该行为的原因
没有 React.StrictMode 的预期工作演示