我有一个表单提交页面, 我有一个useEffect钩子用于Redux错误的变化,所以当错误从后端返回并填充化简器时,它会借助useSelector刷新错误变量,所以我可以在使用Material UI的DOM中显示错误消息
const BugForm = props => {
const { classes } = props;
let error = { image: "", title: "", description: "" };
let modalState = useSelector(state => state.bug.modal);
error = useSelector(state => state.UI.errors);
const initialFormState = {
category: "",
project: "",
priority: "",
viewStatus: "",
resolution: "",
reproducibility: "",
title: "",
description: "",
image: ""
};
const dispatch = useDispatch();
const [value, setValue] = useState({ initialFormState });
const [openErrorSnack, setOpenErrorSnack] = useState(false);
// this is for the useEffect to just fire one time in the load:
const firstUpdate = useRef(true);
useEffect(() => {
if (firstUpdate .current) {
firstUpdate .current = false;
return;
}
setOpenErrorSnack(true);
error.image = "";
}, [error.image || ""]);
//for updating the form values:
const updateField = e => {
setValue({
...value,
[e.target.name]: e.target.value
});
};
当我提交表单时,它会出错,有时当我第一次加载页面时会发生这种情况,有时不会:
TypeError: Cannot read property 'image' of null
BugForm
C:/Users/2C/Desktop/reactjs/ticketApp/client/src/components/bugForm.js:116
113 | }
114 | setOpenSnack(true);
115 | error.image = "";
> 116 | }, [error.image || ""]);
| ^ 117 |
118 | const updateField = e => {
119 | setValue({
这是后期操作:
export const postBug = newBug => dispatch => {
console.log(newBug);
dispatch({ type: LOADING_UI });
checkTokenExpire();
let bodyFormData = new FormData();
Object.keys(newBug).forEach(key => bodyFormData.append(key, newBug[key]));
axios({
method: "post",
url: "http://localhost:5000/api/bugs/",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" }
})
.then(res => {
dispatch({
type: POST_BUG,
payload: res.data
});
dispatch(clearErrors());
dispatch({ type: CHANGE_MODAL });
})
.catch(err => {
dispatch({
type: SET_ERRORS,
payload: err.response.data ? err.response.data : err.response
});
});
};
和用于错误的 UI 缩减器:
const initialState = {
loading: false,
errors: { },
modal: false
};
export default function(state = initialState, action) {
switch (action.type) {
case SET_ERRORS:
return {
...state,
loading: false,
errors: action.payload
};
case CLEAR_ERRORS:
return {
...state,
loading: false,
errors: null
};
case CHANGE_MODAL:
return {
...state,
modal: true
};
default:
return state;
}
}
我该如何解决这个问题,在这种情况下是否有任何正确和安全的方式来使用 useEffect?
清除错误时,在化简器上,将错误设置为 null,以便 useSelector 将 null 返回到变量错误,从而错误。
我认为您可以选择一些替代方案:
- 在清除期间,您可以将错误设置为 {} 而不是 null
- useEffect 在其依赖项中可能存在错误(而不是 error.image(,因此在 useEffect 中,您必须检查错误是否为空 。
此外,我认为使用 let sel 错误是没有用的,因为 useSelector 覆盖了它。 作为编写 adiga,您必须在没有 {} 的情况下设置 initialFormState。 另一个想法:我认为你不能在不使用调度的情况下做 error.image = ">