- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 redux 和 hooks 的初学者。我正在处理表单并尝试通过 useDispatch
Hook 调用操作,但它调用了我的操作两次。
我指的是 this文章。
例子如下:
useProfileForm.js
import { useState, useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchProfile } from '../../../redux/profile/profile.actions';
const useProfileForm = (callback) => {
const profileData = useSelector(state =>
state.profile.items
);
let data;
if (profileData.profile) {
data = profileData.profile;
}
const [values, setValues] = useState(data);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchProfile());
}, [dispatch]);
const handleSubmit = (event) => {
if (event) {
event.preventDefault();
}
callback();
};
const handleChange = (event) => {
event.persist();
setValues(values => ({ ...values, [event.target.name]: event.target.value }));
};
return {
handleChange,
handleSubmit,
values,
}
};
export default useProfileForm;
Action
export const FETCH_PROFILE_BEGIN = "FETCH_PROFILE_BEGIN";
export const FETCH_PROFILE_SUCCESS = "FETCH_PROFILE_SUCCESS";
export const FETCH_PROFILE_FAILURE = "FETCH_PROFILE_FAILURE";
export const ADD_PROFILE_DETAILS = "ADD_PROFILE_DETAILS";
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
function getProfile() {
return fetch("url")
.then(handleErrors)
.then(res => res.json());
}
export function fetchProfile() {
return dispatch => {
dispatch(fetchProfileBegin());
return getProfile().then(json => {
dispatch(fetchProfileSuccess(json));
return json;
}).catch(error =>
dispatch(fetchProfileFailure(error))
);
};
}
export const fetchProfileBegin = () => ({
type: FETCH_PROFILE_BEGIN
});
export const fetchProfileSuccess = profile => {
return {
type: FETCH_PROFILE_SUCCESS,
payload: { profile }
}
};
export const fetchProfileFailure = error => ({
type: FETCH_PROFILE_FAILURE,
payload: { error }
});
export const addProfileDetails = details => {
return {
type: ADD_PROFILE_DETAILS,
payload: details
}
};
reducer :
import { ADD_PROFILE_DETAILS, FETCH_PROFILE_BEGIN, FETCH_PROFILE_FAILURE, FETCH_PROFILE_SUCCESS } from './profile.actions';
const INITIAL_STATE = {
items: [],
loading: false,
error: null
};
const profileReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case ADD_PROFILE_DETAILS:
return {
...state,
addProfileDetails: action.payload
}
case FETCH_PROFILE_BEGIN:
return {
...state,
loading: true,
error: null
};
case FETCH_PROFILE_SUCCESS:
return {
...state,
loading: false,
items: action.payload.profile
};
case FETCH_PROFILE_FAILURE:
return {
...state,
loading: false,
error: action.payload.error,
items: []
};
default:
return state;
}
}
export default profileReducer;
**Component:**
import React from 'react';
import { connect } from 'react-redux';
import useProfileForm from './useProfileForm';
import { addProfileDetails } from '../../../redux/profile/profile.actions';
const EducationalDetails = () => {
const { values, handleChange, handleSubmit } = useProfileForm(submitForm);
console.log("values", values);
function submitForm() {
addProfileDetails(values);
}
if (values) {
if (values.error) {
return <div>Error! {values.error.message}</div>;
}
if (values.loading) {
return <div>Loading...</div>;
}
}
return (
<Card>
...some big html
</Card>
)
}
const mapDispatchToProps = dispatch => ({
addProfileDetails: details => dispatch(details)
});
export default connect(null, mapDispatchToProps)(EducationalDetails);
此外,当我将数据从 const [values, setValues] = useState(data);
useState 传递给 values 时,理想情况下我应该在组件中接收它,但我没有得到它显示未定义。
const { values, handleChange, handleSubmit } = useProfileForm(submitForm);
值未定义
最佳答案
两次分派(dispatch)操作可能是因为您在 React 层次结构中使用了 React.StrictMode
。
根据 react 文档,为了 detect unexpected sideEffects
, react 两次调用某个函数如
Functions passed to useState, useMemo, or useReducer
现在由于 react-redux 是在 react API 之上实现的,所以操作实际上被调用了两次
另外,当我从 const [values, setValues] = useState(data); 传递数据时useState 到值然后理想情况下我应该在组件中收到它,但我没有收到,因为它显示未定义。
要回答这个问题,你必须知道 values 不是来自 reducer 的 dispatch action 的响应结果,而是在调用 handleChange 时更新的状态,因此应该保持不受 action 的影响
我想你的意思是从 useProfileForm
中公开 redux 数据,但忘了做
const useProfileForm = (callback) => {
const profileData = useSelector(state =>
state.profile.items
);
let data;
if (profileData.profile) {
data = profileData.profile;
}
const [values, setValues] = useState(data);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchProfile());
}, [dispatch]);
const handleSubmit = (event) => {
if (event) {
event.preventDefault();
}
callback();
};
const handleChange = (event) => {
event.persist();
setValues(values => ({ ...values, [event.target.name]: event.target.value }));
};
return {
handleChange,
handleSubmit,
values,
data // This is the data coming from redux store on FetchProfile and needs to logged
}
};
export default useProfileForm;
您可以像这样使用组件中的数据
const { values, handleChange, handleSubmit, data } = useProfileForm(submitForm);
关于javascript - Redux + Hooks useDispatch() in useEffect calling action 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62025911/
可以在 function 或 class 中使用 useDispatch Hook 吗?我不是在谈论功能或类组件。我想从函数/类调度状态更改。 // Example: utils.ts export
我正在尝试使用 react-redux 钩子(Hook),但是我得到了错误: TypeError: (0 , _reactRedux.useDispatch) is not a function 有什
我刚开始学习 Redux,但遇到了问题。 我有 Action : export const getValues = () => async (dispatch) => { try {
我一直在使用钩子(Hook)使用 react-redux,但我只是不明白使用 react-redux useDispatch 与仅来自 store 对象的调度函数相比有什么优势。 在 react-re
当我在 useEffect 中使用 useDispatch 时,它会不断重新加载整个组件 这是我的操作: export const getData = () => dispatch => {
嗨,我正在使用 Jest 和 enzyme 编写功能组件测试。当我模拟单击时,组件的参数(使用 useState 的组件状态)会发生变化。并且当状态发生更改时, useEffect 调用并在 useE
我试图在我的 React Native 应用程序中使用 React-Redux,但不知何故出现了这个问题 error: bundling failed: Error: Unable to resolv
我尝试创建一个 Redux,但当我尝试进行分派(dispatch)时遇到问题,但无法正常工作。 Action 文件,userActions.js: export const setId = () =>
我正在使用 redux-thunk使用异步 Action 创建者。结果也返回给各自的调用者。 function fetchUserName(userId: number): Promise { r
我正在尝试创建一个简单的组件来使用 React Redux Hook useDispatch 调度操作- 我得到一个错误。我已将组件修剪到发生错误的位置。它在调用 useDispatch 函数时发生。
我有一个 React hook 组件,onChange 事件将执行 aync-await 函数和一些调度,在我的模型测试中,如果我放置我的,则不会检测到调用 store.dispatch await
在我的 React 代码库中,我集成了 Redux usign react-redux我正在使用 useDispatch从我的 View 中调度操作的钩子(Hook)。我只有一个问题,我在更新商店后无
创建 React 应用程序时,如果我使用 Hook useSelector ,我需要遵守钩子(Hook)调用规则(只能从功能组件的顶层调用它)。如果我使用 mapStateToProps ,我得到了
我正在尝试通过 useDispatch 方法在 redux 中更新我的商店,但我收到这样的消息: Attempted import error: 'useDispatch' is not export
我正在 React-Redux 中尝试 Todo App;运行存储、操作、reducer 和 Addodo 组件;但在显示待办事项时卡住了: 如果我的 initialState=[] 我如何从存储中检
我见过人们像这样制作 Action 创建器(返回 Action 对象以避免拼写错误的函数): // ReduxStuff.js export const makeJuice = flavor => (
我为此找到了很多示例,但没有一个使用 Redux 和 useDispatch ,所以这里的情况...... 我有一个像这样的异步 Action 的 Action 文件...... //postsAct
每当我使用 react 钩子(Hook)安装组件时,我都想获取我的类别 useEffect而不是每次重新渲染。但我不断收到此警告 React Hook useEffect has a missing
我想在首次安装页面时调度一个操作。此操作立即将 loading 设置为 true,然后在 2 秒后将其设置为 false。 注意到当我使用 hooks/react 组件时它有不同的行为。当我使用 co
我正在使用 React、TypeScript、ESlint 和 TypeScript-ESlint。这没有任何问题。 当我安装 Redux、React-Redux 和 @types/react-red
我是一名优秀的程序员,十分优秀!