首页 > 解决方案 > 由于来自 redux 的“错误”变量的变化,useEffect 有时会给出空错误

问题描述

我有一个表单提交页面,有一个 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 reducer 的错误:

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?

标签: javascriptreactjsreduxreact-hooksuse-effect

解决方案


当您清除错误时,在 reducer 上,您将 error 设置为 null,因此 useSelector 将 null 返回到变量 error 和错误。

我认为您可以选择一些替代方案:

  • 在清除期间,您可以将错误设置为 {} 而不是 null
  • useEffect 在其依赖项中可能有错误(而不是 error.image),因此在 useEffect 中您必须检查错误是否为空

此外,我认为使用 let 进行 sel 错误是没有用的,因为 useSelector 会覆盖它。在编写 adiga 时,您必须设置没有 {} 的 initialFormState。另一个想法:我认为你不能在不使用 dispatch 的情况下做 error.image = ""


推荐阅读