Shi*_*ari 0 javascript alert reactjs react-hooks use-reducer
为什么这个警告框在一个简单的 useReducer 应用程序中出现两次,
单击此处 获取代码和框链接,
重新生成场景
这是代码
import "./styles.css";
import { useReducer } from "react";
const reducerFunction = (state, action) => {
switch (action.type) {
case "testing": {
if (action.payload.value > 0) {
return { ...state, testing: action.payload.value };
} else {
alert("some message");
return state;
}
}
default: {
throw new Error("Invalid Action");
}
}
};
export default function App() {
const defaultValue = {
testing: 0
};
const [state, dispatch] = useReducer(reducerFunction, defaultValue);
return (
<input
value={state.testing}
onChange={(e) => {
dispatch({ type: "testing", payload: { value: e.target.value } });
}}
type="number"
/>
);
}
Run Code Online (Sandbox Code Playgroud)
您正在使用StrictModewhich 调用useReducer从文档传递给两次的函数:
\n\n严格模式可以\xe2\x80\x99t 自动为您检测副作用,但它\n可以通过使副作用更具确定性来帮助您发现它们。\n这是通过有意两次调用以下函数来完成的:
\n传递给 useState、useMemo 或 useReducer 的函数
\n
// Remove Strict.Mode\nReactDOM.render(\n <App />,\n rootElement\n);\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1156 次 |
| 最近记录: |